2019.11.13 从零单刷个人笔记整理(持续更新)](https://blog.csdn.net/qq_20304723/article/details/89401203)
github:https://github.com/ChopinXBP/LeetCode-Babel
这题可以有一个直接的思路是用最大堆+归并,对于排序后的数组中的每一个元素nums[i],左侧最小的距离必定为nums[i]-nums[i-1],其后到nums[i]-nums[i-2]……,因此只要进行nums.length路归并,将k个距离加入最大堆,即可求得。
但是这种方法在糟糕情况下可能会超时。标准解法是二分查找,比较难想。
首先要意识到:第k小的距离一定出现在[0, max-min]之中,对此距离进行二分查找。
方法1:二分查找+前缀和
计算sameValue[i]代表在i之前且和i相等的元素个数,计算smallerNums[i]表示≤当前坐标i的元素个数。第k小的距离一定出现在[0, max-min]之中,对此距离进行二分查找,
对于每一个位置i,满足i < j && nums[j]-nums[i] ≤ mid的j的个数为:从nums[i]到nums[i]+mid的元素个数(前缀和) + 在i之前且和i相等的元素个数。因此:
count = smallerNums[nums[i] + mid] - smallerNums[nums[i]] + sameValue[i];
对所有i进行遍历加和,即为≤mid的距离对个数。
方法2:二分查找+双指针
第k小的距离一定出现在[0, max-min]之中,对此距离进行二分查找。对于每一个位置left,满足left< right && nums[right]-nums[left]≤mid的j的个数可以通过双指针遍历求得。
Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B.
给定一个整数数组,返回所有数对之间的第 k 个最小距离。一对 (A, B) 的距离被定义为 A 和 B 之间的绝对差值。
示例 1:
输入:
nums = [1,3,1]
k = 1
输出:0
解释:
所有数对如下:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
因此第 1 个最小距离的数对是 (1,1),它们之间的距离为 0。
提示:
2 <= len(nums) <= 10000.
0 <= nums[i] < 1000000.
1 <= k <= len(nums) * (len(nums) - 1) / 2.
import java.util.Arrays;
/**
*
* Given an integer array, return the k-th smallest distance among all the pairs.
* The distance of a pair (A, B) is defined as the absolute difference between A and B.
* 给定一个整数数组,返回所有数对之间的第 k 个最小距离。一对 (A, B) 的距离被定义为 A 和 B 之间的绝对差值。
*
*/
public class FindKthSmallestPairDistance {
//二分查找+前缀和
public int smallestDistancePair(int[] nums, int k) {
Arrays.sort(nums)