Search for a Range
- Total accepted:91570
- Total submissions:308037
- Difficulty:medium
Given a sorted array of integers, find the starting and ending position of a Given target value.
Your algorithm ' s runtime complexity must is in the order of O(log n).
If the target is not a found in the array, return [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
Return [3, 4]
.
Idea: two points find the leftmost position of the number that matches the condition, and then traverse backwards to find the interval that satisfies the requirement. Code:
1 classSolution {2 Public:3vector<int> Searchrange (vector<int>& Nums,inttarget) {4 intN=nums.size (), low=0, high=n-1, mid;5vector<int>Res;6 while(low<=High ) {7mid=low+ (high-low)/2;8 if(nums[mid]<target) {9Low=mid+1;Ten } One Else{ Ahigh=mid-1; - } - } the if(nums[low]==target) { - res.push_back (low); - while(Low<n&&nums[low]==target) low++; -Res.push_back (low-1); + } - Else{ +Res.push_back (-1); ARes.push_back (-1); at } - returnRes; - } -};
Leetcode 34. Search for a Range