-
Notifications
You must be signed in to change notification settings - Fork 43
/
find-k-closest-elements.py
277 lines (236 loc) · 7.73 KB
/
find-k-closest-elements.py
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""
658. Find K Closest Elements
Medium
Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.
An integer a is closer to x than an integer b if:
|a - x| < |b - x|, or
|a - x| == |b - x| and a < b
Example 1:
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
Example 2:
Input: arr = [1,2,3,4,5], k = 4, x = -1
Output: [1,2,3,4]
Constraints:
1 <= k <= arr.length
1 <= arr.length <= 104
arr is sorted in ascending order.
-104 <= arr[i], x <= 104
"""
# V0
# IDEA : TWO POINTERS
class Solution(object):
def findClosestElements(self, arr, k, x):
while len(arr) > k:
if x - arr[0] <= arr[-1] - x:
arr.pop(-1)
else:
arr.pop(0)
return arr
# V0'
# IDEA : SORTING
class Solution:
def findClosestElements(self, arr, k, x):
# Sort using custom comparator
sorted_arr = sorted(arr, key = lambda num: abs(x - num))
# Only take k elements
result = []
for i in range(k):
result.append(sorted_arr[i])
# Sort again to have output in ascending order
return sorted(result)
# V0''
# IDEA : BINARY SEARCH
class Solution(object):
def findClosestElements(self, arr, k, x):
left = 0
right = len(arr) - k
while left < right:
mid = left + (right - left) // 2
if x - arr[mid] > arr[mid + k] - x:
left = mid + 1
else:
right = mid
return arr[left : left + k]
# V0'''
# IDEA : HASHMAP + brute force
class Solution(object):
def findClosestElements(self, arr, k, x):
# edge case
if k == 0 or not arr:
return []
res = []
d = {}
for i in range(len(arr)):
diff = abs(arr[i]-x)
if diff not in d:
d[diff] = [arr[i]]
else:
d[diff].append(arr[i])
keys = list(d.keys())
keys.sort()
for key in keys:
if len(res) >= k:
break
res += d[key]
ans=res[:k]
ans.sort()
return ans
# V1
# IDEA : Sort With Custom Comparator
# https://leetcode.com/problems/find-k-closest-elements/solution/
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# Sort using custom comparator
sorted_arr = sorted(arr, key = lambda num: abs(x - num))
# Only take k elements
result = []
for i in range(k):
result.append(sorted_arr[i])
# Sort again to have output in ascending order
return sorted(result)
# V1'
# IDEA : Binary Search + Sliding Window
# https://leetcode.com/problems/find-k-closest-elements/solution/
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# Base case
if len(arr) == k:
return arr
# Find the closest element and initialize two pointers
left = bisect_left(arr, x) - 1
right = left + 1
# While the window size is less than k
while right - left - 1 < k:
# Be careful to not go out of bounds
if left == -1:
right += 1
continue
# Expand the window towards the side with the closer number
# Be careful to not go out of bounds with the pointers
if right == len(arr) or abs(arr[left] - x) <= abs(arr[right] - x):
left -= 1
else:
right += 1
# Return the window
return arr[left + 1:right]
# V1''
# IDEA : Binary Search To Find The Left Bound
# https://leetcode.com/problems/find-k-closest-elements/solution/
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# Initialize binary search bounds
left = 0
right = len(arr) - k
# Binary search against the criteria described
while left < right:
mid = (left + right) // 2
if x - arr[mid] > arr[mid + k] - x:
left = mid + 1
else:
right = mid
return arr[left:left + k]
# V1'''
# https://blog.csdn.net/fuxuemingzhu/article/details/82968136
# IDEA : HEAP
class Solution(object):
def findClosestElements(self, arr, k, x):
N = len(arr)
sub = [((arr[i] - x) ** 2, i) for i in range(N)]
heapq.heapify(sub)
return sorted([arr[heapq.heappop(sub)[1]] for i in range(k)])
# V1'''''
# https://blog.csdn.net/fuxuemingzhu/article/details/82968136
# IDEA : TWO POINTERS
class Solution(object):
def findClosestElements(self, arr, k, x):
# since the array already sorted, arr[-1] must be the biggest one,
# while arr[0] is the smallest one
# so if the distance within arr[-1], x > arr[0], x
# then remove the arr[-1] since we want to keep k elements with smaller distance,
# and vice versa (remove arr[0])
while len(arr) > k:
if x - arr[0] <= arr[-1] - x:
arr.pop()
else:
arr.pop(0)
return arr
# V1'''''''
# https://blog.csdn.net/fuxuemingzhu/article/details/82968136
# IDEA : BINARY SEARCH
class Solution(object):
def findClosestElements(self, arr, k, x):
left = 0
right = len(arr) - k
while left < right:
mid = left + (right - left) // 2
if x - arr[mid] > arr[mid + k] - x:
left = mid + 1
else:
right = mid
return arr[left : left + k]
# V1'''''''
# https://www.jiuzhang.com/solution/460-find-k-closest-elements/#tag-highlight-lang-python
class Solution:
# @param {int[]} A an integer array
# @param {int} target an integer
# @param {int} k a non-negative integer
# @return {int[]} an integer array
def kClosestNumbers(self, A, target, k):
# Algorithm:
# 1. Find the first index that A[index] >= target
# 2. Set two pointers left = index - 1 and right = index
# 3. Compare A[left] and A[right] to decide which pointer should move
index = self.firstIndex(A, target)
left, right = index - 1, index
result = []
for i in range(k):
if left < 0:
result.append(A[right])
right += 1
elif right == len(A):
result.append(A[left])
left -= 1
else:
if target - A[left] <= A[right] - target:
result.append(A[left])
left -= 1
else:
result.append(A[right])
right += 1
return result
def firstIndex(self, A, target):
start, end = 0, len(A) - 1
while start + 1 < end:
mid = (start + end) / 2
if A[mid] < target:
start = mid
else:
end = mid
if A[start] >= target:
return start
if A[end] >= target:
return end
return len(A)
# V2
# Time: O(logn + k)
# Space: O(1)
import bisect
class Solution(object):
def findClosestElements(self, arr, k, x):
"""
:type arr: List[int]
:type k: int
:type x: int
:rtype: List[int]
"""
i = bisect.bisect_left(arr, x)
left, right = i-1, i
while k:
if right >= len(arr) or \
(left >= 0 and abs(arr[left]-x) <= abs(arr[right]-x)):
left -= 1
else:
right += 1
k -= 1
return arr[left+1:right]