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

答案

class Solution {
    class MyComparator implements Comparator<int[]> {
        public int compare(int[] a, int[] b) {
            return Integer.compare(a[0] + a[1], b[0] + b[1]);
        }
    }

    public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        List<int[]> ret = new ArrayList<>();
        Comparator<int[]> comparator = new MyComparator();
        PriorityQueue<int[]> pq = new PriorityQueue<int[]>(comparator);

        // form all pairs
        for(int i = 0; i < nums1.length; i++) {
            for(int j = 0; j < nums2.length; j++) {
                int[] t = new int[]{nums1[i], nums2[j]};
                pq.offer(t);
            }
        }
        // poll k pairs and return
        while(!pq.isEmpty() && k > 0) {
            ret.add(pq.poll());
            k--;
        }
        return ret;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容