Skip to content

Commit afa6813

Browse files
authored
Create 658-Find-K-Closest-Elements.py
1 parent 3a8c14a commit afa6813

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

658-Find-K-Closest-Elements.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Log(n) + k
2+
# More code but also more intuitive
3+
class Solution:
4+
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
5+
l, r = 0, len(arr) - 1
6+
7+
# Find index of x or the closest val to x
8+
val, idx = arr[0], 0
9+
while l <= r:
10+
m = (l + r) // 2
11+
curDiff, resDiff = abs(arr[m] - x), abs(val - x)
12+
if (curDiff < resDiff or
13+
(curDiff == resDiff and arr[m] < val)):
14+
val, idx = arr[m], m
15+
16+
if arr[m] < x: l = m + 1
17+
elif arr[m] > x: r = m - 1
18+
else: break
19+
20+
l = r = idx
21+
for i in range(k - 1):
22+
if l == 0:
23+
r += 1
24+
elif r == len(arr) - 1 or x - arr[l-1] <= arr[r+1] - x:
25+
l -= 1
26+
else:
27+
r += 1
28+
return arr[l:r+1]
29+
30+
# Log(n-k) + k
31+
# Elegant but very difficult to understand
32+
class Solution:
33+
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
34+
l, r = 0, len(arr) - k
35+
36+
while l < r:
37+
m = (l + r) // 2
38+
if x - arr[m] > arr[m + k] - x:
39+
l = m + 1
40+
else:
41+
r = m
42+
return arr[l:l+k]

0 commit comments

Comments
 (0)