-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1ST AND LAST OCCURRENCE .cpp
60 lines (57 loc) · 1.36 KB
/
1ST AND LAST OCCURRENCE .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
#include<bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> firstAndLast(vector<int> &arr, int n, int x)
{
// Code here
int mid, s = 0, e = n - 1, ansF = -1;
while (s <= e)
{
mid = (s + e) / 2;
if (arr[mid] == x)
{
ansF = mid;
e = mid - 1;
}
else if (arr[mid] < x)
{
s = mid + 1;
}
else
{
e = mid - 1;
}
}
s = 0, e = n - 1;
int ansL = -1;
while (s <= e)
{
mid = (s + e) / 2;
if (arr[mid] == x)
{
ansL = mid;
s = mid + 1;
}
else if (arr[mid] < x)
{
s = mid + 1;
}
else
{
e = mid - 1;
}
}
vector<int> ans;
if (ansF == -1 || ansL == -1)
{
ans.push_back(-1);
return ans;
}
ans.push_back(ansF);
ans.push_back(ansL);
return ans;
}
};
// GFG