二分查詢
- 找
>=target
的第一個位置 - 找
<=target
的最後一個位置
class Solution {
public:
//找>=target的第一個位置
int binarySearchLeft(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid - 1;//意味著索引>=right+1的陣列值均>=target
}
else {
left = mid + 1;//意味著索引<=left-1的陣列值均<target
}
}
return left;//左閉右閉區間退出迴圈,有left=right+1
}
//找<=target的最後一個位置
int binarySearchRight(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] <= target) {
left = mid + 1;//意味著索引<=left-1的陣列值均<=target
}
else {
right = mid - 1;//意味著索引>=right+1的陣列值均>target
}
}
return right;//左閉右閉區間退出迴圈,有left=right+1
}
vector<int> searchRange(vector<int>& nums, int target) {
int leftIdx = binarySearchLeft(nums, target);
int rightIdx = binarySearchRight(nums, target);
if (leftIdx <= rightIdx && rightIdx < nums.size() && nums[leftIdx] == target && nums[rightIdx] == target) {
return vector<int>{leftIdx, rightIdx};
}
return vector<int>{-1, -1};
}
};
力扣 34. 在排序陣列中查詢元素的第一個位置和最後一個位置