Given an array of integers nums
sorted in ascending order, find the starting and ending position of a given target
value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
Example 1:
Input: nums = [5,7,7,8,8,10]
, target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10]
, target = 6
Output: [-1,-1]
class Solution { public int[] searchRange(int[] nums, int target) { int[] res = {-1,-1}; int left = 0, right = nums.length - 1; int l = -1, r = -1; while(left <= right){ int mid = left + (right-left)/2; if(nums[mid] == target){ l = mid; r = mid; while((l-1) > -1 && nums[l-1] == target){ l--; } while((r+1) < nums.length && nums[r+1] == target){ r++; } break;//!! } else{ if(nums[mid] > target){ right = mid - 1; } else left = mid + 1; } } res[0] = l; res[1] = r; return res; } }
Binary Search。之所以要break是因为一旦所有符号条件的数选完就不会进入到下面的else,也不会更新right和left,所以会有time limit error。因此当得到l和r就应该break。
总结:Using two pointers again, first is to use binary search to find the first target, then make l = mid and r = mid, expand in two directions and break. Then l is the first index, r is the last index. Including the situations that nums.length == 0/1 or only 1 target in array.