-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
39 lines (34 loc) · 960 Bytes
/
Copy pathbinary_search.cpp
File metadata and controls
39 lines (34 loc) · 960 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
class Solution {
public:
/**
* @param nums: The integer array.
* @param target: Target number to find.
* @return: The first position of target. Position starts from 0.
*/
int binarySearch(vector<int> &array, int target) {
// write your code here
if (array.size() == 0) {
return -1;
}
int start = 0;
int end = array.size() - 1;
int mid;
while (start + 1 < end) {
mid = start + (end - start) / 2;
if (array[mid] == target) {
end = mid;
} else if (array[mid] < target) {
start = mid;
} else if (array[mid] > target) {
end = mid;
}
}
if (array[start] == target) {
return start;
}
if (array[end] == target) {
return end;
}
return -1;
}
};