本文主要是介绍[Leetcode]658. Find K Closest Elements,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
# [[Leetcode]658. Find K Closest Elements](https://leetcode.com/problems/find-k-closest-elements/)
- 本题难度: Hard/Medium
- Topic: Data Structure
# Description
# 我的代码
```python
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]
```
这篇关于[Leetcode]658. Find K Closest Elements的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!