二分查找第一个出现target的位置(不断左偏移)

include

include

using namespace std;

int binarySearchFirstOccurrence(vector& nums, int target) {
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 nums = {1, 3, 5, 7, 7, 7, 9, 11, 13};
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;
}

posted @ 2024-12-11 22:52  Qacter  阅读(18)  评论(0)    收藏  举报