【Leetcode】719. Find K-th Smallest Pair Distance

Subject address:

https://leetcode.com/problems/find-k-th-smallest-pair-distance/

Given a length nnArray of n AAA , given two unequal subscriptsiii andjjj , we can always calculate the number pair difference∣ A [i] − A [j] ∣ |A[i]-A[j]|A[i]A [ j ] . Given a positive integerkkk , askkkWhat is the difference of such a number with small k ? The order of the subscripts is different, it is also regarded as the same number pair.

The idea is a dichotomous answer. If AAThe maximum value of A isMMM , the minimum value ismmm , the biggest difference is obviouslyM − m MmMm , the minimum difference is0 00 . We can divide the answer into two divisions, each time a numberxxx , just look at how many pairs of numbers are less than or equal to it, if it is greater than or equal tokkk , then the final answer is not greater thanxxx , then shrink the right margin toxxx ; otherwise, the final answer is greater thanxxx , then shrink the left margin tox + 1 x+1x+1 . Calculation ratioxxThe number of x less than or equal to the number of differences can be done with sort + double pointer. After sorting the array, open two pointersiii andjjj keepi> j i>ji>j (because the number pair cannot be repeated), if the number pair difference is greater thanxxx , then move the left pointer to the right until the logarithmic difference is less than or equal to orj = ij=ij=i until i , and then accumulatei − j ijij (herei − j ijij Ze以A [i] A [i]A [ i ] is the larger value and the logarithmic difference is less than or equal toxxThe number of pairs of x ). Note that there is no need to roll back the left pointer. The reason is that rollback will only result in a larger number-to-pair difference and no answer. code show as below:

import java.util.Arrays;

public class Solution {
    
    
    public int smallestDistancePair(int[] nums, int k) {
    
    
        if (nums == null || nums.length == 0) {
    
    
            return 0;
        }
        
        Arrays.sort(nums);
        
        int l = 0, r = nums[nums.length - 1] - nums[0];
        while (l < r) {
    
    
            int m = l + (r - l >> 1);
            // 计算一下小于等于m的数对差的个数
            int count = 0;
            for (int i = 0, j = 0; i < nums.length; i++) {
    
    
                while (j < i && nums[i] - nums[j] > m) {
    
    
                    j++;
                }
                
                count += i - j;
            }
            
            // 如果小于等于m的数对差的个数大于等于k,则收缩右边界,否则收缩左边界
            if (count >= k) {
    
    
                r = m;
            } else {
    
    
                l = m + 1;
            }
        }
        
        return l;
    }
}

Time complexity O (n (log ⁡ (M − m) + n)) O(n(\log (Mm) + n))O(n(log(Mm)+n)) M M M is the maximum value of the array,mmm is the minimum value of the array, spaceO (1) O (1)O ( 1 )

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/113028920