-
Notifications
You must be signed in to change notification settings - Fork 0
/
Search for a Range.cpp
53 lines (51 loc) · 1.35 KB
/
Search for a Range.cpp
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
49
50
51
52
53
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> nomatch;
nomatch.push_back(-1);
nomatch.push_back(-1);
if (target<A[0] || A[n-1]<target) {
return nomatch;
}
int begin=0;
int end=n;
while(begin<end){
if(A[begin]==target) {
break;
}
if (end-begin==1 && A[begin]!=target) {
return nomatch;
}
int middle = (begin+end+1)/2;
if (A[middle-1]<target) {
begin=middle;
}
else {
end=middle;
}
}
vector<int>ret;
ret.push_back(begin);
begin=0;
end=n;
while(begin<end){
if(A[end-1]==target) {
break;
}
if (end-begin==1 && A[begin]!=target) {
return nomatch;
}
int middle = (begin+end+1)/2;
if (A[middle]>target) {
end=middle;
}
else {
begin=middle;
}
}
ret.push_back(end-1);
return ret;
}
};