373. Find K Pairs with Smallest Sums

Question

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:

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]


Code

public class Solution {
    public class Tuple {
        public int index1;
        public int index2;
        public int value1;
        public int value2;
        public Tuple(int index1, int index2, int value1, int value2) {
            this.index1 = index1;
            this.index2 = index2;
            this.value1 = value1;
            this.value2 = value2;
        }
    }
    
    public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        List<int[]> result = new ArrayList<>();
        if (k == 0 || nums1.length == 0 || nums2.length == 0) return result;
        
        PriorityQueue<Tuple> pq = new PriorityQueue<>(new Comparator<Tuple>() {
            public int compare(Tuple t1, Tuple t2) {
                return (t1.value1 + t1.value2) - (t2.value1 + t2.value2);
            }    
        });
        for (int i = 0; i < nums1.length; i++) {
            Tuple tuple = new Tuple(i, 0, nums1[i], nums2[0]);
            pq.offer(tuple);
        }
        while (pq.size() > 0 && result.size() < k) {
            Tuple tuple = pq.poll();
            
            int[] t = new int[2];
            t[0] = tuple.value1;
            t[1] = tuple.value2;
            result.add(t);
            
            if (tuple.index2 + 1 < nums2.length) {
                tuple.index2++;
                tuple.value2 = nums2[tuple.index2];
                pq.offer(tuple);
            }
        }
        
        return result;
    }
}

Solution

使用PriorityQueue解決。

自定義一個二元組Tuple,其中含有nums1中某元素的下標index1和值value1以及nums2中某元素的下標index2和值value2。

定義一個PriorityQueue,排序是按照Tuple中value1和value2的和排序。

初始化時,將nums1中所有元素與nums2中第一個元素組成Tuple,加入隊列中。

循環(huán),彈出隊列中第一個元素,將元素的value1和value2加入結(jié)果集中。并將元素的index2 + 1,value2更新后,重新加入隊列中。循環(huán)直至結(jié)果集大小為k或隊列為空。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容