-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeeetcodeM_658_find_k_closest_element
115 lines (102 loc) · 2.24 KB
/
LeeetcodeM_658_find_k_closest_element
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Method 1 Two ptr approach Tc =O (N-K) ; SC = O(K)
class Solution {
public:
vector<int> twopointermethod(vector<int> &arr, int k, int x)
{
int l=0, h =arr.size()-1;
while(h-l>=k)
{
if(x-arr[l] > arr[h]-x)
{
l++;
}
else
{
h--;
}
}
vector<int> ans;
for(int i=l;i<=h;i++)
{
ans.push_back(arr[i]);
}
return ans;
}
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
return twopointermethod(arr, k, x);
}
};
//Method 2 Two ptr approach Tc =O (N-K) ; SC = O(1)
class Solution {
public:
vector<int> twopointermethod(vector<int> &arr, int k, int x)
{
int l=0, h =arr.size()-1;
while(h-l>=k)
{
if(x-arr[l] > arr[h]-x)
{
l++;
}
else
{
h--;
}
}
return vector<int>(arr.begin()+l , arr.begin()+h+1);
}
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
return twopointermethod(arr, k, x);
}
};
// Method 03 - Binary search ,method
class Solution {
public:
int lowerbound(vector<int> &arr, int x)
{
int start=0, end = arr.size()-1;
int ans =end;
while(start<=end)
{
int mid = (start + end)/2;
if(arr[mid]>=x)
{
ans= mid;
end =mid-1;
}
else if(x>arr[mid])
{
start = mid +1;
}
else
{
end = mid -1;
}
}
return ans;
}
vector<int> bs_method(vector<int> &arr, int k, int x)
{
int h = lowerbound(arr,x);
int l = h-1;
while(k--)
{
if(l<0)
{
h++;
}
else if(h >= arr.size()){
l--;
}
else if(x - arr[l] > arr[h] - x){
h++;
}
else
l--;
}
return vector<int>(arr.begin()+ l + 1, arr.begin()+h);
}
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
return bs_method(arr, k, x);
}
};