此次咱们仍是要改造二分搜索,可是想法却有一点不同。java
查找问题,时间复杂度要求对数级别的,咱们天然的想到了二分查找,和上一题同样,需求都是有点不同的,此次是有重复的数字,找出某一特定的重复的数组的起始和结束位置,咱们依旧要是有二分查找,不过,当找到了目标值的时候,不能直接返回,须要判断这个数值的左右是否有一样的数字,若是左右都有,则继续左右搜索,若是左有右没有则记录结束为止而且向左搜索,若是右有左没有,则记录左节点而且向右搜索。算法
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; } }
经过改造二分搜索,咱们能够获得正确的答案,可是咱们一样也看到了,算法的简练渡和通用性的重要意义。数组