Movatterモバイル変換


[0]ホーム

URL:


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

Adding an improved solution for Problem: 658. Find K Closest Elements#3865

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
praxkv-labs wants to merge1 commit intoneetcode-gh:main
base:main
Choose a base branch
Loading
frompraxkv-labs:users/Prakash/2025-Fix_K_closestElement
Open
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 22 additions & 22 deletionspython/0658-find-k-closest-elements.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,32 +2,32 @@
# More code but also more intuitive
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
l, r = 0, len(arr) - 1
# Step 1: Binary Search to find the closest position to x
left, right = 0, len(arr) - 1
while left < right:
mid = (left + right) // 2
if arr[mid] < x:
left = mid + 1
else:
right = mid

# Find index of x or the closest val to x
val, idx = arr[0], 0
while l <= r:
m = (l + r) // 2
curDiff, resDiff = abs(arr[m] - x), abs(val - x)
if curDiff < resDiff or (curDiff == resDiff and arr[m] < val):
val, idx = arr[m], m
# Step 2: Initialize two pointers around the closest element
left, right = left - 1, left # left points to smaller, right points to larger

if arr[m] < x:
l = m + 1
elif arr[m] > x:
r = m - 1
# Step 3: Expand around the closest position to find k elements
while k > 0:
if left < 0: # If left pointer is out of bounds, move right
right += 1
elif right >= len(arr): # If right pointer is out of bounds, move left
left -= 1
elif abs(arr[left] - x) <= abs(arr[right] - x): # Pick the closer element
left -= 1
else:
break
right += 1
k -= 1

l = r = idx
for i in range(k - 1):
if l == 0:
r += 1
elif r == len(arr) - 1 or x - arr[l - 1] <= arr[r + 1] - x:
l -= 1
else:
r += 1
return arr[l : r + 1]
# Step 4: Return the sorted subarray
return arr[left + 1:right]


# Log(n-k) + k
Expand Down

[8]ページ先頭

©2009-2025 Movatter.jp