-
Notifications
You must be signed in to change notification settings - Fork 0
/
0034.searchRange
34 lines (32 loc) · 1.09 KB
/
0034.searchRange
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
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int n = nums.size();
int before = binarySearchBefore(nums, target, n) + 1;
int after = binarySearchAfter(nums, target, n) - 1;
if(before <= after && before >=0 && after < n && nums[before] == target && nums[after] == target)
return {before, after};
return {-1, -1};
}
private:
int binarySearchBefore(vector<int>& nums, int target, const int &n) {
if (nums.empty()) return -1;
int left = 0, right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] >= target) right = mid - 1;
else left = mid + 1;
}
return right;
}
int binarySearchAfter(vector<int>& nums, int target, const int &n) {
if (nums.empty()) return -1;
int left = 0, right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] > target) right = mid - 1;
else left = mid + 1;
}
return left;
}
};