前言
在笔试的时候,二分查找法容易写错一些细节导致最后的结果是错的;
// 该二分查找的目的是在一个有序序列中找到第一个大于等于target的下标
int bin_find(vector<int> nums, int target)
{
int start = 0, end = nums.size() - 1;
bool is_find = false;
if (target <= nums[start]) return start;
if (target > nums[end]) return -1;
while (start <= end) {
int mid = (start + end) / 2;
if (mid > 0 && nums[mid] >= target && nums[mid - 1] < target) {
return mid;
}
if (nums[mid] > target)
end = mid - 1;
else
start = mid + 1;
}
return -1;
}
// 二分查找法,判断一个数是否存在于一个有序序列中
int binary_find_exist(vector<int> nums, int target)
{
int start = 0, end = nums.size() - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (nums[mid] == target)
return mid;
else if (nums[mid] > target)
end = mid - 1;
else
start = mid + 1;
}
return -1;
}
int main() {
vector<int> temp({1,2,4,6,7,9,11});
int index = bin_find(temp, 7);
if (index == -1)
cout << "can not find!!!" << endl;
else
cout << "index = " << index << " nums[index] = "<< temp[index] << endl;
return 0;
}
网友评论