Skip to content

Commit fecbbcc

Browse files
committed
add k closest elements in array python
1 parent b1a51d4 commit fecbbcc

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Python/K_Closest_Elements.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
def findClosestElements(arr, k, x):
2+
"""
3+
:type arr: List[int]
4+
:type k: int
5+
:type x: int
6+
:rtype: List[int]
7+
"""
8+
#Set left and right pointers, right is k less than len
9+
left, right = 0, len(arr) - k
10+
#As long as left is less than right
11+
while left < right:
12+
#Find the mid point of left and right
13+
mid = (left + right) // 2
14+
#If the mid point less targer is greater than
15+
if (x - arr[mid]) > (arr[mid + k] - x):
16+
left = mid + 1
17+
else:
18+
right = mid
19+
return arr[left:left + k]
20+
21+
def insertSorted(arr, x):
22+
i = 0
23+
while i < len(arr):
24+
if arr[i] >= x:
25+
arr.insert(i, x)
26+
return arr
27+
i += 1
28+
return arr + [x]
29+
30+
print(findClosestElements([1, 2, 3, 4, 5, 6], 2, 3))
31+
print(insertSorted([1, 2, 3, 4, 5], 0.4))

0 commit comments

Comments
 (0)