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 106ed64

Browse files
🐱(binary-search): 719. 找出第 k 小的距离对
1 parent 173b494 commit 106ed64

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎docs/algorithm/research/binary-search/README.md‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1008,6 +1008,45 @@ class Solution:
10081008
return arr[left:left + k]
10091009
```
10101010

1011+
## 719. 找出第 k 小的距离对
1012+
1013+
[原题链接](https://leetcode-cn.com/problems/find-k-th-smallest-pair-distance/)
1014+
1015+
### 解一:二分查找 + 双指针
1016+
1017+
- k 值落在 `[0, max(nums) - min(nums)]` 中,此为二分查找范围
1018+
- 以此范围内的值查找小于该值的距离对数量
1019+
1020+
```python
1021+
class Solution:
1022+
def smallestDistancePair(self, nums: List[int], k: int) -> int:
1023+
nums.sort()
1024+
1025+
def get_mid_count(target):
1026+
# 双指针
1027+
i, count = 0, 0
1028+
for j in range(1, len(nums)):
1029+
while nums[j] - nums[i] > target:
1030+
i += 1
1031+
count += j - i
1032+
return count
1033+
1034+
# 第 k 小距离在 [left, right] 之间
1035+
left = 0
1036+
right = nums[-1] - nums[0]
1037+
while left < right:
1038+
mid = (left + right) // 2
1039+
# 计算小于等于 mid 的数量
1040+
count = get_mid_count(mid)
1041+
if count >= k:
1042+
# 如果数量大于 k,说明 mid 大了或就是结果
1043+
right = mid
1044+
else:
1045+
# 如果数量小于 k,说明 mid 小了
1046+
left = mid + 1
1047+
return left
1048+
```
1049+
10111050
## 744. 寻找比目标字母大的最小字母
10121051

10131052
[原题链接](https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target/)

0 commit comments

Comments
(0)

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