美文网首页
2020-04-12 34. Find First and La

2020-04-12 34. Find First and La

作者: _伦_ | 来源:发表于2020-04-12 10:54 被阅读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;

        }

    }

    相关文章

      网友评论

          本文标题:2020-04-12 34. Find First and La

          本文链接:https://www.haomeiwen.com/subject/fdrvmhtx.html