搜索最左侧target 的 index(在排序数组中查找元素的第一个和最后一个位置):
int binarySearchMostLeftIndex(vector<int> & nums, int target)
{
int left = 0;
int right = nums.size() - 1;
int ans = nums.size();
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] >= target) {
right = mid - 1;
ans = mid;
}else {
left = mid + 1;
}
}
return ans;
}
搜索最右侧target 的 index:
int binarySearchMostRightIndex(vector<int> & nums, int target)
{
int left = 0;
int right = nums.size() - 1;
int ans = nums.size();
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] > target) {
right = mid - 1;
}else {
left = mid + 1;
ans = mid;
}
}
return ans;
}