-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path0704.cpp
More file actions
48 lines (42 loc) · 1.17 KB
/
0704.cpp
File metadata and controls
48 lines (42 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/******************************************************************************
* 文件名: 0704
* 作者: BOLUN XU
* 创建日期: 2025
* 版本: 1.0
* 描述: 二分查找。
* 时间复杂度:O(LogN)
* 空间复杂度:O(1)
* 执行用时:0 ms
* 消耗内存:30.66 mb
******************************************************************************/
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
int search(vector<int>& nums, int target) {
// if (nums.empty() || target < nums[0] || target > nums[nums.size() - 1]) return -1;
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
}
else if (nums[mid] > target) {
right = mid - 1;
}
else if (nums[mid] == target) {
return mid;
}
}
return -1;
}
};
int main() {
Solution sol;
vector<int> nums = {-1,0,3,5,9,12};
int target = 2;
cout << sol.search(nums, target) << endl;
return 0;
}