Given an array of integers 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].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
思路:时间复杂度为O(log n),首先想到二分法,其次再确定二分判断关系和坐标转移关系。
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> res(2, -1);
if(nums.empty()) return res;
int n = nums.size();
int left = 0, right = n - 1;
while(left < right) {
int mid = (left+right) / 2;
if(target > nums[mid]) { // 二分关系确保left为最左边坐标
left = mid + 1;
} else {
right = mid;
}
}
if(nums[left] != target) return res;
res[0] = left;
right = n-1;
while(left < right) {
int mid = (left+right) / 2 + 1; // 加1确保不会出现死循环
if(target < nums[mid]) {
right = mid - 1;
} else {
left = mid;
}
}
res[1] = right;
return res;
}
};