題目:
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]
題目要求log(n)複雜度,考慮用二分查找。首先二分法定位查找target,再以當前定位target的index分別向左和向右二分查找左端點和右端點。
代碼
class Solution {
public:
// 先二分查找target,再二分查找最左端index和最右端index
vector<int> searchRange(vector<int>& nums, int target) {
int index = -1, left = 0, right = nums.size()-1;
vector<int> vec(2,-1);
while(left <= right){ //二分查找尋找數組中是否存在target
int mid = (left+right)/2;
if(nums[mid] < target ) left = mid+1;
else if(nums[mid] > target) right = mid-1;
else{
index = mid;
break;
}
}
if(index == -1) return vec; //不存在直接返回[-1,-1]
int min_left = 0, min_right = index, max_left = index, max_right = nums.size()-1;
while(min_left <= min_right){ // 二分法尋找最左端的index
int mid = (min_left + min_right)/2;
if(nums[mid] < target) min_left = mid+1;
else min_right = mid-1;
}
while(max_left <= max_right){ // 二分法尋找最右端的index
int mid = (max_left+max_right)/2;
if(nums[mid] > target) max_right = mid-1;
else max_left = mid+1;
}
vec[0] = min_left;
vec[1] = max_right;
return vec;
}
};