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:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> res = {-1,-1};
res[0] = bt_search(nums,target,true);
res[1] = bt_search(nums,target,false);
return res;
}
int bt_search(vector<int>& a, int target, bool left) {
int low = 0;
int high = a.size()-1;
bool find = false;
while(low <= high) {
int mid = low + (high - low) / 2;
if(a[mid] < target) {
low = mid + 1 ;
} else if (target < a[mid]){
high = mid - 1 ;
} else {
if (left) high = mid - 1;
else low = mid + 1;
find = true;
}
}
if(!find) return -1;
if(left) return low;
else return low-1;
}
};
二分查找左边的target ,二分查找右边的target
左边的话,是 a[mid]<=t lo = mid+1
右边的话 是 a[mid]>=t hi = mid -1
1 class Solution(object): 2 def searchRange(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: List[int] 7 """ 8 # write code here 9 def fun_r(a, target): 10 lo = 0 11 hi = len(a) - 1 12 13 while(lo <= hi): 14 mid = lo + int((hi - lo) / 2) 15 if(target <= a[mid]): 16 hi = mid - 1 17 else: 18 lo = mid + 1 19 return lo 20 21 def fun_l(a, target): 22 lo = 0 23 hi = len(a) - 1 24 25 while(lo <= hi): 26 mid = lo + int((hi - lo) / 2) 27 if(target < a[mid]): 28 hi = mid - 1 29 else: 30 lo = mid + 1 31 return hi 32 33 34 r = fun_r(nums, target) 35 l = fun_l(nums, target) 36 if r>len(nums)-1 or l<0: 37 return [-1,-1] 38 if nums[r]!=nums[l] : 39 return [-1,-1] 40 return [ r,l] 41