373-找出前k对和最小

Description

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 (u1,v1),(u2,v2) …(uk,vk) with the smallest sums.


Example 1:

Given nums1 = [1,7,11], nums2 = [2,4,6],  k = 3

Return: [1,2],[1,4],[1,6]

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:

Given nums1 = [1,1,2], nums2 = [1,2,3],  k = 2

Return: [1,1],[1,1]

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:

Given nums1 = [1,2], nums2 = [3],  k = 3 

Return: [1,3],[2,3]

All possible pairs are returned from the sequence:
[1,3],[2,3]

问题描述

给定排序整数数组nums1和nums2, 以及整数k
定义一对(u, v), 为从nums1和nums2中各自挑选一个元素组成
找出k对最小和的(u1,v1),(u2,v2) …(uk,vk)


问题分析

minHeap为优先级队列,排序规则为元素之和

先将nums1[0]和nums2[i] (0 < i < nums2.length) 的组合放入minHeap中,每当从minHeap中poll一对,需要加入新的组合,令poll出的对为(i, j)(i表示取自nums1的i号元素,j表示取自nums2的j号元素),那么新加入的组合为(i + 1, j)。


解法

class Solution {
    public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        List<int[]> ans = new ArrayList();
        //优先级队列,Tuple实现了Comparable接口中的compareTo方法,排序规则为元素之和
        PriorityQueue minHeap = new PriorityQueue();
        if (nums1.length == 0 || nums2.length == 0) return ans;
        //先将这些组合放进来
        for (int i = 0; i < nums2.length; i++) {
            minHeap.offer(new Tuple(0, i, nums1[0] + nums2[i]));
        }

        for (int i = 0; i < Math.min(k, nums1.length * nums2.length); i++) {
            Tuple cur = minHeap.poll();
            ans.add(new int[] {nums1[cur.index1], nums2[cur.index2]});
            if (cur.index1 + 1 < nums1.length) {
                //注意这里添加新的对的规则
                minHeap.offer(new Tuple(cur.index1 + 1, cur.index2, nums1[cur.index1 + 1] + nums2[cur.index2]));
            }
        }

        return ans;

    }
}

class Tuple implements Comparable<Tuple>{
    public int index1;
    public int index2;
    public Integer val;
    public Tuple(int index1, int index2, int val) {
        this.index1 = index1;
        this.index2 = index2;
        this.val = val;
    }
    public int compareTo(Tuple that) {
        return this.val.compareTo(that.val);
    }
}

你可能感兴趣的:(算法与数据结构,leetcode全解)