forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search-for-a-range.cpp
69 lines (62 loc) · 1.81 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Time: O(logn)
// Space: O(1)
class Solution {
/**
*@param A : an integer sorted array
*@param target : an integer to be inserted
*return : a list of length 2, [index1, index2]
*/
public:
vector<int> searchRange(vector<int> &A, int target) {
const auto start = lower_bound(A.cbegin(), A.cend(), target);
const auto end = upper_bound(A.cbegin(), A.cend(), target);
if (start != A.cend() && *start == target) {
return {start - A.cbegin(), end - A.cbegin() - 1};
}
return {-1, -1};
}
};
class Solution2 {
/**
*@param A : an integer sorted array
*@param target : an integer to be inserted
*return : a list of length 2, [index1, index2]
*/
public:
vector<int> searchRange(vector<int> &A, int target) {
const int begin = lower_bound(A, target);
const int end = upper_bound(A, target);
if (begin < A.size() && A[begin] == target)
return {begin, end - 1};
return {-1, -1};
}
private:
int lower_bound(vector<int> &A, int target) {
int left = 0;
int right = A.size();
// Find min left s.t. A[left] >= target.
while (left < right) {
int mid = left + (right - left) / 2;
if (A[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
int upper_bound(vector<int> &A, int target) {
int left = 0;
int right = A.size();
// Find min left s.t. A[left] > target.
while (left < right) {
int mid = left + (right - left) / 2;
if (A[mid] > target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
};