forked from arkingc/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
34.cpp
48 lines (41 loc) · 1.21 KB
/
34.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
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int l = searchRangel(nums,target);
int r = searchRanger(nums,target);
vector<int> v;
v.push_back(l);
v.push_back(r);
return v;
}
int searchRangel(const vector<int> &nums,int target)
{
int l = 0,r = nums.size() - 1;
int mid;
while(l <= r){
mid = (l + r) / 2;
if(nums[mid] == target){
if(mid == 0 || nums[mid - 1] != nums[mid]) return mid;
else r = mid - 1;
}
else if(nums[mid] > target) r = mid - 1;
else l = mid + 1;
}
return -1;
}
int searchRanger(const vector<int> &nums,int target)
{
int l = 0,r = nums.size() - 1;
int mid,end = r;
while(l <= r){
mid = (l + r) / 2;
if(nums[mid] == target){
if(mid == end || nums[mid + 1] != nums[mid]) return mid;
else l = mid + 1;
}
else if(nums[mid] > target) r = mid - 1;
else l = mid + 1;
}
return -1;
}
};