【LeetCode】373. Find K Pairs with Smallest Sums 查找和最小的K对数字(Medium)(JAVA)
题目地址: https://leetcode.com/problems/find-k-pairs-with-smallest-sums/
题目描述:
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
Define a pair (u,v) which consists of one element from the first array and one element from the second array.
Find the k pairs (u_1,v_1),(u_2,v_2) …(u_k,v_k) with the smallest sums.
Example 1:
Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Output: [[1,2],[1,4],[1,6]]
Explanation: The first 3 pairs are returned from the sequence:
[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
Example 2:
Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
Output: [1,1],[1,1]
Explanation: The first 2 pairs are returned from the sequence:
[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
Example 3:
Input: nums1 = [1,2], nums2 = [3], k = 3
Output: [1,3],[2,3]
Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]
题目大意
给定两个以升序排列的整形数组 nums1 和 nums2, 以及一个整数 k。
定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2。
找到和最小的 k 对数字 (u_1,v_1), (u_2,v_2) … (u_k,v_k)。
解题方法
- 类似求 Top K 的问题,这里用一个最大堆来存储 k 个最小的元素,堆顶元素就是 k 个最小元素的最大值
- 前 k 个元素放到最大堆里面,k 个元素之后,判断当前元素是否比堆顶的小,如果小就把最大的去除,把当前元素放进去
- note: java 可以用 PriorityQueue 优先队列来实现最大堆
class Solution {
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
PriorityQueue<List<Integer>> queue = new PriorityQueue<>(k, (l1, l2) -> (l2.get(0) + l2.get(1) - l1.get(0) - l1.get(1)));
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums2.length; j++) {
if (queue.size() < k) {
List<Integer> temp = new ArrayList<>();
temp.add(nums1[i]);
temp.add(nums2[j]);
queue.offer(temp);
continue;
}
List<Integer> last = queue.peek();
if (last.get(0) + last.get(1) <= nums1[i] + nums2[j]) {
break;
} else {
queue.poll();
List<Integer> temp = new ArrayList<>();
temp.add(nums1[i]);
temp.add(nums2[j]);
queue.offer(temp);
}
}
}
List<List<Integer>> list = new ArrayList<>();
while (queue.size() > 0) {
list.add(0, queue.poll());
}
return list;
}
}
执行耗时:14 ms,击败了60.27% 的Java用户
内存消耗:39.4 MB,击败了63.88% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg#pic_center)