Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d1afc7f

Browse files
authored
Add files via upload
1 parent 264572f commit d1afc7f

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
def binary_search(array, target):
2+
left = 0
3+
right = len(array) - 1
4+
while left <= right:
5+
mid = (left + right) // 2
6+
if array[mid] == target:
7+
return mid
8+
if array[mid] < target:
9+
left = mid + 1
10+
else:
11+
right = mid - 1
12+
return left
13+
14+
15+
16+
##################################################################
17+
18+
19+
20+
def find_closest_elements(nums, k, target):
21+
22+
# Check if length of nums is same as k
23+
if len(nums) == k:
24+
return nums
25+
26+
# Check if target is less than or equal to first element of nums
27+
if target <= nums[0]:
28+
return nums[0:k]
29+
30+
# Check if target is greater than or equal to last element of nums
31+
if target >= nums[-1]:
32+
return nums[len(nums) - k: len(nums)]
33+
34+
# Find first closest element to target using binary search
35+
first_closest = binary_search(nums, target)
36+
37+
# Initialize sliding window pointers
38+
window_left = first_closest - 1
39+
window_right = window_left + 1
40+
41+
# Expand sliding window until equal to k
42+
while (window_right - window_left -1) < k:
43+
44+
# Move window right
45+
if window_left == -1:
46+
window_right += 1
47+
continue
48+
49+
# Move window left
50+
if window_right == len(nums) or abs(nums[window_left] - target) <= abs(nums[window_right] - target):
51+
window_left -= 1
52+
53+
# Move window right
54+
else:
55+
window_right += 1
56+
57+
# Return k closest elements
58+
return nums[window_left + 1 : window_right]
59+
60+
61+
62+
# Time Complexity = O(logn + k)
63+
# Space Complexity = O(1)
64+
65+
66+
67+
##################################################################
68+
69+
70+
71+
# Driver code
72+
def main():
73+
74+
nums = [
75+
[1, 2, 3, 5, 6, 7,8],
76+
[1, 2, 3, 4, 5],
77+
[1, 2, 4, 5, 6],
78+
[1, 2, 3, 4, 5, 10]
79+
]
80+
k = [4, 4, 2, 3]
81+
num = [4, 3, 10, -5]
82+
for i in range(len(nums)):
83+
print((i + 1), ".\tThe ", k[i],
84+
" Closest Elements for the number ", num[i], " in the array ",
85+
nums[i], " are:", sep="")
86+
print("\t", find_closest_elements(nums[i], k[i], num[i]))
87+
print("-" * 100)
88+
89+
if __name__ == '__main__':
90+
main()
91+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /