https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
Given an array of integers
nums
sorted in ascending order, find the starting and ending position of a giventarget
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]
二分搜索上下界,用的邓俊辉的理解方法,很直观。
搜索上界时,hi及hi的右侧满足>target,lo的左侧满足<=target,因此当lo==hi时,lo-1即为target应在位置的上界
搜索下界时,lo及lo的左侧满足<target,hi的右侧满足>=target,因此当lo==hi时,hi+1即为target应在位置的下界
注意在搜索下界时要确保每一次迭代问题的潜在解空间会缩小,即每一步都必须要移动两侧边界,所以mid = (lo+hi+1)/2
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int hi = search_up(nums, target);
if(hi == -1 || nums[hi] != target) return {-1, -1};
int lo = search_down(nums, target);
return {lo, hi};
}
int search_up(vector<int>& nums, int target){
int lo = 0;
int hi = nums.size();
int mid;
while(lo < hi){
mid = (lo+hi)/2;
if(nums[mid] > target) hi = mid;
else lo = mid+1;
}
return lo-1;
}
int search_down(vector<int>& nums, int target){
int lo = -1;
int hi = nums.size()-1;
int mid;
while(lo < hi){
mid = (lo+hi+1)/2;
if(nums[mid] < target) lo = mid;
else hi = mid-1;
}
return lo+1;
}
};