-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq5_binary_search.cpp
More file actions
42 lines (36 loc) · 845 Bytes
/
q5_binary_search.cpp
File metadata and controls
42 lines (36 loc) · 845 Bytes
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
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int search(vector<int>& nums, int target) {
int head = 0;
int tail = nums.size()-1;
while (head < tail){
if (nums[(head+tail)/2] == target){
cout<<(head+tail)/2<<endl;
return (head+tail)/2;
}
else if (nums[(head+tail)/2] < target){
head = (head+tail)/2 + 1;
}
else{
tail = (head+tail)/2 -1;
}
}
if (nums[(head+tail)/2] != target){
cout<<"-1"<<endl;
return -1;
}
return 0;
}
};
int main()
{
Solution s;
vector<int> nums = {-1,0,3,5,9,12};
s.search(nums, 9);
return 0;
}