leetcode_cpp/search/704.cpp
2021-12-22 13:23:43 +08:00

42 lines
917 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* @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;
}