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 {
        public int compare(int[] a, int[] b) {
            return Integer.compare(a[0] + a[1], b[0] + b[1]);
        }
    }

    public List kSmallestPairs(int[] nums1, int[] nums2, int k) {
        List ret = new ArrayList<>();
        Comparator comparator = new MyComparator();
        PriorityQueue pq = new PriorityQueue(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;
    }
}

你可能感兴趣的:(Find K Pairs with Smallest Sums)