此次咱們仍是要改造二分搜索,可是想法卻有一點不同。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; } }
經過改造二分搜索,咱們能夠獲得正確的答案,可是咱們一樣也看到了,算法的簡練渡和通用性的重要意義。數組