|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +/** |
| 4 | + * You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. |
| 5 | + * |
| 6 | + * Define a pair (u,v) which consists of one element from the first array and one element from the second array. |
| 7 | + * |
| 8 | + * Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums. |
| 9 | + * |
| 10 | + * Example 1: |
| 11 | + * |
| 12 | + * Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 |
| 13 | + * Output: [[1,2],[1,4],[1,6]] |
| 14 | + * Explanation: The first 3 pairs are returned from the sequence: |
| 15 | + * [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] |
| 16 | + * Example 2: |
| 17 | + * |
| 18 | + * Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2 |
| 19 | + * Output: [1,1],[1,1] |
| 20 | + * Explanation: The first 2 pairs are returned from the sequence: |
| 21 | + * [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] |
| 22 | + * Example 3: |
| 23 | + * |
| 24 | + * Input: nums1 = [1,2], nums2 = [3], k = 3 |
| 25 | + * Output: [1,3],[2,3] |
| 26 | + * Explanation: All possible pairs are returned from the sequence: [1,3],[2,3] |
| 27 | + */ |
| 28 | +public class Leetcode_373_140 { |
| 29 | + |
| 30 | + public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) { |
| 31 | + Queue<int []> maxHeap = new PriorityQueue<>(k, (a, b) -> (b[0] + b[1] - a[0] - a[1])); |
| 32 | + |
| 33 | + for(int num1 : nums1) { |
| 34 | + for(int num2 : nums2) { |
| 35 | + int [] a = new int[] {num1, num2}; |
| 36 | + |
| 37 | + int sum = num1 + num2; |
| 38 | + |
| 39 | + if(maxHeap.size() >= k) { |
| 40 | + int [] max = maxHeap.peek(); |
| 41 | + if(sum < max[0] + max[1]) { |
| 42 | + maxHeap.poll(); |
| 43 | + maxHeap.offer(a); |
| 44 | + } |
| 45 | + } else { |
| 46 | + maxHeap.offer(a); |
| 47 | + } |
| 48 | + |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + List<int []> ans = new LinkedList<>(); |
| 53 | + while(!maxHeap.isEmpty()) { |
| 54 | + ans.add(maxHeap.poll()); |
| 55 | + } |
| 56 | + |
| 57 | + Collections.reverse(ans); |
| 58 | + |
| 59 | + return ans; |
| 60 | + } |
| 61 | +} |
0 commit comments