-
Notifications
You must be signed in to change notification settings - Fork 0
/
searchRange.cpp
45 lines (36 loc) · 929 Bytes
/
searchRange.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
#include <vector>
using namespace std;
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans = vector<int>{-1,-1};
if(nums.empty()) return ans;
int n = nums.size();
int first = 0, end = n-1;
int mid = 0;
while(first <= end){
mid = (first+end)/2;
if(nums[mid] == target && (mid == n-1 || nums[mid] < nums[mid+1])){
ans[1] = mid;
break;
}
else if(nums[mid] > target){
end = mid-1;
}else{
first = mid + 1;
}
}
first = 0, end = n-1;
mid = 0;
while(first <= end){
mid = (first+end)/2;
if(nums[mid] == target && (mid == 0 || nums[mid] > nums[mid-1])){
ans[0] = mid;
break;
}
else if(nums[mid] >= target){
end = mid-1;
}else{
first = mid + 1;
}
}
return ans;
}