LeetCode第34题:Find First and Last Position of Element in Sorted Array在有序数组中寻找初始和结

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 20:51   1538   0

题目描述:

我的解答:

class Solution {
    //最简单的方法,分别从左边找和从右边找
    public int[] searchRange(int[] nums, int target) {
        int[] targetIndex = {-1, -1};

        //从左边找
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                targetIndex[0] = i;
                break;
            }
        }

        // 如果左边没有,就说明nums中没有这个target
        if (targetIndex[0] == -1) {
            return targetIndex;
        }

        // 从右边开始找
        for (int j = nums.length-1; j >= 0; j--) {
            if (nums[j] == target) {
                targetIndex[1] = j;
                break;
            }
        }

        return targetIndex;
    }
}

运行结果:

另外一种方法:

class Solution {
    // returns leftmost (or rightmost) index at which `target` should be
    // inserted in sorted array `nums` via binary search.
    private int extremeInsertionIndex(int[] nums, int target, boolean left) {
        int lo = 0;
        int hi = nums.length;

        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (nums[mid] > target || (left && target == nums[mid])) {
                hi = mid;
            }
            else {
                lo = mid+1;
            }
        }

        return lo;
    }

    public int[] searchRange(int[] nums, int target) {
        int[] targetRange = {-1, -1};

        int leftIdx = extremeInsertionIndex(nums, target, true);

        // assert that `leftIdx` is within the array bounds and that `target`
        // is actually in `nums`.
        if (leftIdx == nums.length || nums[leftIdx] != target) {
            return targetRange;
        }

        targetRange[0] = leftIdx;
        targetRange[1] = extremeInsertionIndex(nums, target, false)-1;

        return targetRange;
    }
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP