LeetCode 题解工作台
找出第 K 小的数对距离
数对 (a,b) 由整数 a 和 b 组成,其数对距离定义为 a 和 b 的绝对差值。 给你一个整数数组 nums 和一个整数 k ,数对由 nums[i] 和 nums[j] 组成且满足 0 。返回 所有数对距离中 第 k 小的数对距离。 示例 1: 输入: nums = [1,3,1], k =…
4
题型
6
代码语言
3
相关题
当前训练重点
困难 · 二分·搜索·答案·空间
答案摘要
先对 数组进行排序,然后在 $[0, nums[n-1]-nums[0]]$ 范围内二分枚举数对距离 ,若 中数对距离小于等于 的数量 大于等于 ,则尝试缩小 ,否则尝试扩大 。 时间复杂度 ,其中 表示 的长度, 表示 中两个数的最大差值。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
数对 (a,b) 由整数 a 和 b 组成,其数对距离定义为 a 和 b 的绝对差值。
给你一个整数数组 nums 和一个整数 k ,数对由 nums[i] 和 nums[j] 组成且满足 0 <= i < j < nums.length 。返回 所有数对距离中 第 k 小的数对距离。
示例 1:
输入:nums = [1,3,1], k = 1 输出:0 解释:数对和对应的距离如下: (1,3) -> 2 (1,1) -> 0 (3,1) -> 2 距离第 1 小的数对是 (1,1) ,距离为 0 。
示例 2:
输入:nums = [1,1,1], k = 2 输出:0
示例 3:
输入:nums = [1,6,1], k = 3 输出:5
提示:
n == nums.length2 <= n <= 1040 <= nums[i] <= 1061 <= k <= n * (n - 1) / 2
解题思路
方法一:排序 + 二分查找
先对 数组进行排序,然后在 范围内二分枚举数对距离 ,若 中数对距离小于等于 的数量 大于等于 ,则尝试缩小 ,否则尝试扩大 。
时间复杂度 ,其中 表示 的长度, 表示 中两个数的最大差值。
class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
def count(dist):
cnt = 0
for i, b in enumerate(nums):
a = b - dist
j = bisect_left(nums, a, 0, i)
cnt += i - j
return cnt
nums.sort()
return bisect_left(range(nums[-1] - nums[0]), k, key=count)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n \log M + n \log n) |
| 空间 | O(S) |
面试官常问的追问
外企场景- question_mark
They hint to binary search the answer space instead of enumerating all pair distances.
- question_mark
They ask how to count pairs with distance <= X efficiently after sorting.
- question_mark
They push back on O(n^2) generation, which usually means the two-pointer counting check is the missing piece.
常见陷阱
外企场景- error
Binary searching pair positions instead of binary searching the distance value itself.
- error
Using a nested scan for each mid, which turns the counting check back into O(n^2).
- error
Moving the left pointer incorrectly and undercounting or overcounting pairs when nums[right] - nums[left] exceeds mid.
进阶变体
外企场景- arrow_right_alt
Return the k-th largest pair distance, which flips how you reason about the count threshold.
- arrow_right_alt
Count pairs with distance strictly less than X instead of less than or equal to X, which changes the boundary condition.
- arrow_right_alt
Solve the same answer-space search when the array contains many duplicates, where zero-distance pairs dominate early ranks.