-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirst_last_x.cpp
More file actions
61 lines (55 loc) · 1.06 KB
/
first_last_x.cpp
File metadata and controls
61 lines (55 loc) · 1.06 KB
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
vector<int> find(int arr[], int n , int x )
{
int f = -1, l = -1;
vector<int> res;
for(int i=0; i<n; i++){
if(arr[i] == x && f == -1){
f = i;
l = i;
}
else if(arr[i] == x){
l = i;
}
}
res.push_back(f);
res.push_back(l);
return res;
}
//O(n)
vector<int> find(int arr[], int n , int x )
{
vector<int> res;
int l , r,v;
l = 0, r = n - 1, v = -1;
while(l <= r){
int mid = l + (r - l)/2;
if(arr[mid] > x){
r = mid -1;
}
else if(arr[mid] < x){
l = mid + 1;
}
else{
v = mid;
r = mid - 1;
}
}
res.push_back(v);
l = 0, r = n -1, v = -1;
while(l <= r){
int mid = l + (r - l)/2;
if(arr[mid] > x){
r = mid -1;
}
else if(arr[mid] < x){
l = mid + 1;
}
else{
v = mid;
l = mid + 1;
}
}
res.push_back(v);
return res;
}
//O(log(n))