当前位置: 代码迷 >> 综合 >> Leetcode 658. Find K Closest Elements
  详细解决方案

Leetcode 658. Find K Closest Elements

热度:31   发布时间:2023-12-12 21:11:50.0

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Find K Closest Elements

2. Solution

  • Version 1
class Solution:def findClosestElements(self, arr, k, x):result = []index = self.binarySearch(arr, x)left = indexright = index + 1length = len(arr)while k:if left < 0:result = result + [arr[right]]right += 1elif right >= length:result = [arr[left]] + resultleft -= 1elif x - arr[left] <= arr[right] - x:result = [arr[left]] + resultleft -= 1else:result = result + [arr[right]]right += 1k -= 1return resultdef binarySearch(self, arr, x):left = 0right = len(arr) - 1index = 0while left <= right:middle = (left + right) // 2if arr[middle] < x:index = leftleft += 1elif arr[middle] > x:right -=1index = rightelse:return middlereturn index
  • Version 2
class Solution:def findClosestElements(self, arr, k, x):left = 0right = len(arr) - kwhile left < right:middle = (left + right) // 2if x - arr[middle] >  arr[middle + k] - x:left = middle + 1else:right = middlereturn arr[left:left+k]

Reference

  1. https://leetcode.com/problems/find-k-closest-elements/
  相关解决方案