Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 18ed7bb

Browse files
committed
Update binary_search.md
找到k个最近元素
1 parent bf8d5fd commit 18ed7bb

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

‎basic_algorithm/binary_search.md‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,41 @@ int findTarget(vector<int>& nums, int target, bool findLeft){
245245

246246
}
247247
```
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+
248283

249284
### [search-insert-position](https://leetcode-cn.com/problems/search-insert-position/)
250285

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /