42 lines
917 B
C++
42 lines
917 B
C++
/*
|
||
* @Description:
|
||
* @Version: 1.0
|
||
* @Autor: zhuyijun
|
||
* @Date: 2021-12-21 13:33:03
|
||
* @LastEditTime: 2021-12-21 13:51:30
|
||
*/
|
||
//二分查找
|
||
/*
|
||
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target
|
||
,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
|
||
|
||
|
||
示例 1:
|
||
|
||
输入: nums = [-1,0,3,5,9,12], target = 9
|
||
输出: 4
|
||
解释: 9 出现在 nums 中并且下标为 4
|
||
|
||
*/
|
||
#include <bits/stdc++.h>
|
||
using namespace std;
|
||
int search(vector<int>& nums, int target) {
|
||
int low = 0, high = nums.size() - 1;
|
||
while (low <= high) {
|
||
int mid = (high - low) / 2 + low;
|
||
int num = nums[mid];
|
||
if (num == target) {
|
||
return mid;
|
||
} else if (num > target) {
|
||
high = mid - 1;
|
||
} else {
|
||
low = mid + 1;
|
||
}
|
||
}
|
||
return -1;
|
||
}
|
||
int main() {
|
||
vector<int> li = {1, 2, 3, 4, 5, 6, 7};
|
||
cout << search(li, 1);
|
||
return 0;
|
||
} |