原题目:https://leetcode-cn.com/problems/find-k-th-smallest-pair-distance/
题目:
给定一个整数数组,返回所有数对之间的第 k 个最小距离。一对 (A, B) 的距离被定义为 A 和 B 之间的绝对差值。
示例:
输入:
nums = [1,3,1]
k = 1
输出:0
解释:
所有数对如下:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
因此第 1 个最小距离的数对是 (1,1),它们之间的距离为 0。
Python3解法:二分查找和双指针,注释解析
class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
# 排序
nums.sort()
# 最小为0,最大也就首尾差
left, right = 0, nums[-1] - nums[0]
while left < right:
# 二分搜索,先确定中值mid
mid = (left + right) // 2
# 双指针,一个计数count,一个遍历start
count, start = 0, 0
# 双指针遍历,确定count
for i in range(len(nums)):
# 数组已排序,当距离差大于mid时,start加1,进入下一个遍历
while nums[i] - nums[start] > mid:
start += 1
count += i - start
# 二分搜索
if count < k:
left = mid + 1
else:
right = mid
return left
结果: