题目:给定两个以升序排列的整形数组 nums1 和 nums2, 以及一个整数 k。定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2。找到和最小的 k 对数字 (u1,v1), (u2,v2) ... (uk,vk)。Leetcode373
示例 1:
输入: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 输出: [1,2],[1,4],[1,6]
解释: 返回序列中的前 3 对数: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
思路:
将所有和可视化为矩阵,最小的一定是左上角,选出3之后,下一个肯定是3的右边或下边,可用堆来实现。
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
PriorityQueue<Tuple> q = new PriorityQueue<>();
List<List<Integer>> res = new ArrayList<>();
List<Integer> one = new ArrayList<>();
if(nums1==null || nums1.length==0 || nums2==null || nums2.length==0){
return res;
}
int m = nums1.length;
int n = nums2.length;
for(int i=0;i<n;i++){
q.add(new Tuple(0,i,nums1[0]+nums2[i]));
}
for(int j=0;j<Math.min(k,m*n);j++){
Tuple t = q.poll();
one.add(nums1[t.x]);
one.add(nums2[t.y]);
res.add(new ArrayList<Integer>(one));
one.clear();
if(t.x==m-1){
continue;
}
q.add(new Tuple(t.x+1,t.y,nums1[t.x+1]+nums2[t.y]));
}
return res;
}
class Tuple implements Comparable<Tuple>{
int x,y,val;
public Tuple(int x,int y,int val){
this.x = x;
this.y = y;
this.val = val;
}
public int compareTo(Tuple that){
return this.val - that.val;
}
同样的解法适用于 Leetcode378
题目:给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。
请注意,它是排序后的第k小元素,而不是第k个元素。
示例:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
], k = 8, 返回 13。
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
PriorityQueue<Tuple> q = new PriorityQueue<>();
for(int i=0;i<n;i++){
q.add(new Tuple(0,i,matrix[0][i]));
}
for(int j=0;j<k-1;j++){
Tuple t = q.poll();
if(t.x==n-1){
continue;
}
q.add(new Tuple(t.x+1,t.y,matrix[t.x+1][t.y]));
}
return q.poll().val;
}
class Tuple implements Comparable<Tuple>{
int x, y, val;
public Tuple(int x,int y,int val){
this.x = x;
this.y = y;
this.val = val;
}
public int compareTo(Tuple that){
return this.val - that.val;
}
}