二分查找
- 找
>=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. 在排序数组中查找元素的第一个位置和最后一个位置
标签:二分,right,target,nums,int,vector,算法,查找,left From: https://www.cnblogs.com/milkchocolateicecream/p/18471804