xinyu04

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

统计

LeetCode 658. Find K Closest Elements 二分+双指针

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

Solution

先用二分确定 x 的位置,然后用双指针来确定左右范围

点击查看代码
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
def left_bound(arr, x):
left = 0
right = len(arr)
while left<right:
mid = left+int((right-left)/2)
if arr[mid]==x:
right=mid
elif arr[mid]<x:
left=mid+1
elif arr[mid]>x:
right=mid
return left
right = left_bound(arr,x)
left = right-1
print(right, left)
for _ in range(k):
if left<0:
right+=1
elif right>=len(arr):
left-=1
else:
if x-arr[left]<=arr[right]-x:
left-=1
else:
right+=1
return arr[left+1:right]

posted on   Blackzxy  阅读(8)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
历史上的今天:
2022-07-15 LeetCode Largest Rectangle in Histogram 思维
2022-07-15 LeetCode Longest Increasing Path in a Matrix 记忆化搜索+DP [Hard]
点击右上角即可分享
微信分享提示