719-找出第k小的对距离

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LaputaFallen/article/details/79949532

Description:

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:

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

问题描述
给定整数数组,返回所有对中的第k小的距离。(A, B)对的距离为A和B的差的绝对值。


问题分析
这种题目的套路是找出上下界,以某种标准(或者计数方式)通过二分查找求解。如果对这种类型的题目不是很了解的话,可以看看这个链接,总结得非常详细:
https://leetcode.com/problems/k-th-smallest-prime-fraction/discuss/115819/Summary-of-solutions-for-problems-%22reducible%22-to-LeetCode-378


解法

class Solution {
    public int smallestDistancePair(int[] nums, int k) {
        //注意这里,对数组进行排序处理
        Arrays.sort(nums);

        int len = nums.length;

        int left = 0, right = nums[len - 1] - nums[0];

        while(left < right){
            int mid = left + (right - left) / 2;
            int count = getCount(nums, mid);
            //注意这里的二分查找左边界和右边界更新的标准
            //小于k,mid必然非最终解,因此left = mid + 1
            //大于等于k,可以将mid作为候选解
            if(count < k)   left = mid + 1;
            else            right = mid;
        }

        return left;
    }
    //计数方式
    public int getCount(int[] nums, int mid){
        int count = 0;

        int left = 0;
        //注意这里的left,在迭代的过程中没有重置,而是一直右移
        //很容易理解,i右移,nums[i]变大(注意对数组进行过排序),而nums[left](上一轮的)不变
        //因此差增大,必然还是比mid大,因此不需要再迭代一遍
        for(int i = 1; i < nums.length;i++){
            while(nums[i] - nums[left] > mid)   left++;
            count += i - left;
        }

        return count;
    }
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页