LeetCode719. Find K-th Smallest Pair Distance (hard)

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.

Example 1:

Input:
nums = [1,3,1]
k = 1
Output: 0 
Explanation:
Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.

Note:

class
   dfaf

  1. 2 <= len(nums) <= 10000.
  2. 0 <= nums[i] < 1000000.
  3. 1 <= k <= len(nums) * (len(nums) - 1) / 2.

这道题暴力破解的思想非常简单,但是会超时,所以找到其他的解决方法,这道题我想了很久,但是没有想到方法,只好去看Solution

首先对数组进行排序,然后选择距离的最大边界和最小边界,最小边界设置为0,最大边界就是排序后的数组的最后一个元素减去数组的第一个元素。知道了最大距离和最小距离,这里采用二分查找类似的思想,但是对其进行稍微的改动,假设最大距离和最小距离的中间值为m,然后定义一个count来计数,用来存储小于m的个数,如果这个个数大于目标k,那么我们就通过减小m来继续进行比较,如果小于m,那就增大m,这里都采用二分查找的思想。

然后找到大于m的距离的个数是另一个不容易想到的点,或者说稍微有点难度的点,我们设置一个左边的索引和一个右边的索引left 和right,先让右边不动,如果距离大于m,则让left向右移动,用while控制这个判断,然后知道跳出来,跳出来之后,统计right到从left到right的的个数,比如,right到left,right到left+1....所以个数是right-left。这里比Solution里面多了一个判断,这样判断可以减少多余的判断次数,如果count>k直接跳出,因为没有必要继续统计下去,因为减小m的值。


然后直接返回l,因为跳出了l<h的循环,所以所求即使l。

 
  1. class Solution {
  2. public int smallestDistancePair(int[] nums, int k) {
  3. Arrays.sort(nums);
  4. int l = 0;
  5. int h = nums[nums.length-1]-nums[0];
  6. while(l<h){
  7. int m = (h+l)/2;
  8. int left = 0,count = 0;
  9. for(int right = 0;right<nums.length;++right){
  10. while(nums[right]-nums[left]>m) left++;
  11. count +=right - left;
  12. if(count>k) break;
  13. }
  14. if(count>=k) h = m;
  15. else l = m + 1;
  16. }
  17. return l;
  18. }
  19. }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值