二分查找第一个出现target的位置(不断左偏移)
include
include
using namespace std;
int binarySearchFirstOccurrence(vector
int left = 0;
int right = nums.size() - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
result = mid;
right = mid - 1; // 继续向左搜索
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
int main() {
vector
int target = 7;
int index = binarySearchFirstOccurrence(nums, target);
if (index!= -1) {
cout << "The first index of " << target << " is " << index << endl;
} else {
cout << target << " is not found in the array." << endl;
}
return 0;
}

浙公网安备 33010602011771号