719. 找出第 k 小的距离对
作者:互联网
给定一个整数数组,返回所有数对之间的第 k 个最小距离。一对 (A, B) 的距离被定义为 A 和 B 之间的绝对差值。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-k-th-smallest-pair-distance
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
堆(超时)
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
class Solution {
public int smallestDistancePair(int[] nums, int k) {
Arrays.sort(nums);
PriorityQueue<Node> heap = new PriorityQueue<>(nums.length,
Comparator.comparingInt(node -> nums[node.nei] - nums[node.root]));
for (int i = 0; i + 1 < nums.length; ++i) {
heap.offer(new Node(i, i + 1));
}
Node node = null;
for (; k > 0; --k) {
node = heap.poll();
if (node.nei + 1 < nums.length) {
heap.offer(new Node(node.root, node.nei + 1));
}
}
return nums[node.nei] - nums[node.root];
}
}
class Node {
int root;
int nei;
Node(int r, int n) {
root = r;
nei = n;
}
}
二分
import java.util.Arrays;
class Solution {
public int smallestDistancePair(int[] nums, int k) {
Arrays.sort(nums);
int ans = 0;
int lo = 0;
int hi = nums[nums.length - 1] - nums[0];
while (lo <= hi) {
int mi = (lo + hi) >> 1;
int count = 0, left = 0;
for (int right = 0; right < nums.length; ++right) {
while (nums[right] - nums[left] > mi) {
left++;
}
count += right - left;
}
if (count >= k) {
ans = mi;
hi = mi - 1;
} else {
lo = mi + 1;
}
}
return ans;
}
public static void main(String[] args) {
int[] nums = {1, 6, 1};
int k = 1;
System.out.println(new Solution().smallestDistancePair(nums, 1));
}
}
标签:node,找出,right,719,nums,int,nei,距离,length 来源: https://www.cnblogs.com/tianyiya/p/15827450.html