-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0034 - Find First and Last Position of Element in Sorted Array.cpp
59 lines (52 loc) · 1.49 KB
/
0034 - 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
class Solution
{
public:
int check(vector<int> &V, int mid, int target)
{
if(V[mid] == target) return 1;
else if(V[mid] > target) return 2;
else return 0;
}
int lastOccurance(vector<int> &V, int target)
{
int N = V.size();
int low = 0, high = N-1;
int ans = -1;
while(low <= high)
{
int mid = low + (high - low) / 2;
if(int flag = check(V, mid, target))
{
if(flag == 1)
{
ans = mid;
low = mid + 1;
}
else high = mid - 1;
}
else low = mid +1;
}
return ans;
}
int firstOccurance(vector<int> &V, int target)
{
int N = V.size();
int low = 0, high = N-1;
int ans = -1;
while(low <= high)
{
int mid = low + (high - low) / 2;
if(int flag = check(V, mid, target))
{
if(flag == 1) ans = mid;
high = mid - 1;
}
else low = mid + 1;
}
return ans;
}
vector<int> searchRange(vector<int>& nums, int target)
{
return {firstOccurance(nums, target), lastOccurance(nums, target)};
}
};