[Leetcode]658. Find K Closest Elements
[Leetcode]658. Find K Closest Elements
- 本题难度: Hard/Medium
- Topic: Data Structure
Description
我的代码
import bisect
class Solution:
def findClosestElements(self, arr,k,x):
l = len(arr)
sorted(arr)
f = bisect.bisect_left(arr,x)
if (f == l) or (f>0 and x - arr[f-1] < arr[f] - x):
f = f-1
if f == l -1:
return arr[-k:]
head = f-k-1 if f-k-1>0 else 0
while(head+k-1<l-1 and arr[head+k] - x < x - arr[head]):
head+=1
return arr[head:head+k]