-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path34. Find First and Last Position of Element in Sorted Array.cpp
67 lines (63 loc) · 1.51 KB
/
34. Find First and Last Position of Element in Sorted Array.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
class Solution {
public:
int binarysearch(vector<int> &nums,int x)
{
long l = 0;
int h = nums.size()-1;
long ans = -1;
while( l <= h )
{
long mid = (l +h )/2;
if( nums[mid] >= x )
{
// cout<<nums[mid] <<endl;
ans = mid;
h = mid -1;
}
else
{
// cout<< mid <<" false"<<endl;
l = mid +1;
}
}
if( ans!= -1 && nums[ans] != x)
return -1;
return ans;
}
int binarysearch2(vector<int> &nums,int x)
{
long l = 0;
int h = nums.size()-1;
long ans = -1;
while( l <= h )
{
long mid = (l +h )/2;
if( nums[mid] <= x )
{
// cout<<mid <<endl;
ans = mid;
l = mid +1;
}
else
{
// cout<< mid <<" false"<<endl;
h = mid -1;
}
}
if( ans !=-1 && nums[ans] != x)
return -1;
return ans;
}
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans;
if( !nums.size() )
{
ans.push_back(-1);
ans.push_back(-1);
return ans;
}
ans.push_back(binarysearch(nums,target));
ans.push_back(binarysearch2(nums,target));
return ans;
}
};