2020-04-12 34. Find First and La

2020-04-12  本文已影响0人  _伦_

这题如果分别写两个二分查找,还比较简单;如果想写同一个函数做两次二分,就有多一些边界情况要考虑:

class Solution {

    public int[] searchRange(int[] nums, int target) {

        if (nums == null || nums.length == 0) return new int[]{-1, -1};

        int first = findFirstGreaterOrEqualsTo(nums, target, 0);

        if (first == nums.length || nums[first] != target) return new int[]{-1, -1};

        int last = findFirstGreaterOrEqualsTo(nums, target + 1, first + 1) - 1;

        return new int[]{first, last};

    }

    int findFirstGreaterOrEqualsTo(int[] nums, int target, int start) {

        int l = start, r = nums.length;

        // System.out.println("find first...");

        while (l < r) {

            // System.out.println("l: " + l + " r: " + r);

            int mid = l + (r - l) / 2, midVal = nums[mid];

            if (midVal >= target) {

                r = mid;

            } else {

                l = mid + 1;

            }

        }

        return l;

    }

}

上一篇下一篇

猜你喜欢

热点阅读