forked from cmhungsteve/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search-for-a-range.cpp
59 lines (53 loc) · 1.58 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
// Time: O(logn)
// Space: O(1)
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
const auto start = lower_bound(nums.cbegin(), nums.cend(), target);
const auto end = upper_bound(nums.cbegin(), nums.cend(), target);
if (start != nums.cend() && *start == target) {
return {start - nums.cbegin(), end - nums.cbegin() - 1};
}
return {-1, -1};
}
};
class Solution2 {
public:
vector<int> searchRange(vector<int> &nums, int target) {
const int begin = lower_bound(nums, target);
const int end = upper_bound(nums, target);
if (begin < nums.size() && nums[begin] == target) {
return {begin, end - 1};
}
return {-1, -1};
}
private:
int lower_bound(vector<int> &nums, int target) {
int left = 0;
int right = nums.size();
// Find min left s.t. A[left] >= target.
while (left < right) {
const auto mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
int upper_bound(vector<int> &nums, int target) {
int left = 0;
int right = nums.size();
// Find min left s.t. A[left] > target.
while (left < right) {
const auto mid = left + (right - left) / 2;
if (nums[mid] > target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
};