373. Find K Pairs with Smallest Sums

题目链接:https://leetcode.com/problems...

greedy: 先把一组x里面和另外一组y最小元素的组合放进heap,然后每次poll出和最小的,同时放进去有可能成为第二小的组合,即当前y元素的下一个和x元素的组合。

public class Solution {
    public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
        if(nums1.length == 0 || nums2.length == 0)  return new ArrayList();
        
        // heap: [nums1[i], nums2[j], i, j]
        PriorityQueue<int[]> minHeap = new PriorityQueue<>(k, (a, b) -> a[0] + a[1] - (b[0] + b[1]));
        // add combination of element from one array with the first element of another
        for(int i = 0; i < Math.min(nums1.length, k); i++) {
            minHeap.offer(new int[] {nums1[i], nums2[0], i, 0});
        }
        // greedy
        List<int[]> result = new ArrayList();
        while(k-- > 0 && !minHeap.isEmpty()) {
            int[] cur = minHeap.poll();
            int i = cur[2], j = cur[3];
            result.add(new int[] {cur[0], cur[1]});
            if(j + 1 < nums2.length) minHeap.offer(new int[] {nums1[i], nums2[j + 1], i, j + 1});
        }
        
        return result;
    }
}

lulouch13
13 声望6 粉丝