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 b1927a7

Browse files
committed
Update binary_search.md
K个最近子数组
1 parent 56bad73 commit b1927a7

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

‎basic_algorithm/binary_search.md‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ int findTarget(vector<int>& nums, int target, bool findLeft){
251251
思路有好几种:
252252
253253
1. 找到最小值,然后双指针
254-
2. 直接找k成都的子序列
254+
2. 直接找k长度的子序列
255255
3. 删去最远的剩下的就是最近的长度为k的子数组
256256
257257
@@ -279,7 +279,27 @@ class Solution:
279279
return res
280280
```
281281

282-
282+
```python
283+
### 方法二
284+
class Solution:
285+
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
286+
'''
287+
直接定位mid为左边界;
288+
查找mid+k的结果是否满足要求;
289+
不满足的话二分法左右调整mid.
290+
'''
291+
if len(arr) == k: return arr
292+
left, right = 0, len(arr) - k
293+
while left + 1 < right:
294+
mid = left + (right - left) // 2
295+
if x - arr[mid] <= arr[mid + k] - x:
296+
right = mid
297+
else:
298+
left = mid
299+
300+
if abs(arr[left] - x) <= abs(arr[right + k - 1] - x): return arr[left: left + k]
301+
else: return arr[right: right + k]
302+
```
283303

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

0 commit comments

Comments
(0)

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