-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearch for a Range.txt
43 lines (43 loc) · 1.25 KB
/
Search for a Range.txt
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
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> ret(2, -1);
if ((n == 0) || (target < A[0]) || (target > A[n-1]))
return ret;
ret[0] = findFirst(A, n, target);
ret[1] = findLast(A, n, target);
return ret;
}
int findFirst(int A[], int n, int target) {
int l = 0, u = n - 1, mid;
while (l <= u) {
mid = (l+u)/2;
if (target == A[mid]) {
if ((mid == 0) || (A[mid-1] != A[mid]))
return mid;
u = mid - 1;
} else if (target < A[mid])
u = mid - 1;
else
l = mid + 1;
}
return -1;
}
int findLast(int A[], int n, int target) {
int l = 0, u = n - 1, mid;
while (l <= u) {
mid = (l+u)/2;
if (target == A[mid]) {
if ((mid == n - 1) || (A[mid+1] != A[mid]))
return mid;
l = mid + 1;
} else if (target < A[mid])
u = mid - 1;
else
l = mid + 1;
}
return -1;
}
};