@@ -245,6 +245,41 @@ int findTarget(vector<int>& nums, int target, bool findLeft){
245
245
246
246
}
247
247
```
248
+ ### [找到k个最接近的元素](https://leetcode.cn/problems/find-k-closest-elements/)
249
+ > 给定一个 排序好 的数组 arr ,两个整数 k 和 x ,从数组中找到最靠近 x(两数之差最小)的 k 个数。返回的结果必须要是按升序排好的。
250
+
251
+ 思路有好几种:
252
+
253
+ 1. 找到最小值,然后双指针
254
+ 2. 直接找k的子序列
255
+ 3. 删去最远的剩下的就是最近的k个子数组
256
+
257
+
258
+ **Python版本**
259
+ ```python
260
+ ### 方法一
261
+ class Solution:
262
+ def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
263
+ if len(arr) == k: return arr
264
+ left, right = 0, len(arr) - 1
265
+
266
+ while left + 1 < right:
267
+ mid = left + (right - left) // 2
268
+ if arr[mid] >= x: right = mid
269
+ else: left = mid
270
+
271
+ res = list()
272
+ while len(res) < k:
273
+ if right >= len(arr) or (left >= 0 and abs(arr[left]-x) <= abs(arr[right]-x)):
274
+ res.insert(0, arr[left])
275
+ left = left - 1
276
+ else:
277
+ res.append(arr[right])
278
+ right = right + 1
279
+ return res
280
+ ```
281
+
282
+
248
283
249
284
### [ search-insert-position] ( https://leetcode-cn.com/problems/search-insert-position/ )
250
285
0 commit comments