|
1 |
| -class Solution { |
2 |
| - public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) { |
3 |
| - List<int[]> ans = new ArrayList<>(); |
4 |
| - |
5 |
| - if (nums1.length == 0 || nums2.length == 0 || k == 0) { |
6 |
| - return ans; |
7 |
| - } |
8 |
| - |
9 |
| - PriorityQueue<Element> pq = new PriorityQueue<>(new Comparator<Element>() { |
10 |
| - @Override |
11 |
| - public int compare(Element o1, Element o2) { |
12 |
| - return (o1.x + o1.y) - (o2.x + o2.y); |
13 |
| - } |
14 |
| - }); |
15 |
| - |
16 |
| - for (int i=0; i<nums2.length && i < k; i++) { |
17 |
| - pq.offer(new Element(0, nums2[i], nums1[0])); |
18 |
| - } |
19 |
| - |
| 1 | +class Solution { |
| 2 | + public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) { |
| 3 | + PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[2] - b[2]); |
| 4 | + List<List<Integer>> result = new ArrayList<>(); |
| 5 | + Set<Pair<Integer, Integer>> visited = new HashSet<>(); |
| 6 | + pq.add(new int[]{0, 0, nums1[0] + nums2[0]}); |
| 7 | + visited.add(new Pair<Integer, Integer>(0, 0)); |
20 | 8 | while (k-- > 0 && !pq.isEmpty()) {
|
21 |
| - Element temp = pq.poll(); |
22 |
| - ans.add(new int[]{temp.y, temp.x}); |
23 |
| - |
24 |
| - if (temp.idx >= nums1.length-1) { |
25 |
| - continue; |
| 9 | + int[] removed = pq.poll(); |
| 10 | + int i = removed[0]; |
| 11 | + int j = removed[1]; |
| 12 | + result.add(List.of(nums1[i], nums2[j])); |
| 13 | + Pair<Integer, Integer> nums1Pair = new Pair<Integer, Integer>(i + 1, j); |
| 14 | + Pair<Integer, Integer> nums2Pair = new Pair<Integer, Integer>(i, j + 1); |
| 15 | + if (i + 1 < nums1.length && !visited.contains(nums1Pair)) { |
| 16 | + pq.add(new int[]{i + 1, j, nums1[i + 1] + nums2[j]}); |
| 17 | + visited.add(nums1Pair); |
| 18 | + } |
| 19 | + if (j + 1 < nums2.length && !visited.contains(nums2Pair)) { |
| 20 | + pq.add(new int[]{i, j + 1, nums1[i] + nums2[j + 1]}); |
| 21 | + visited.add(nums2Pair); |
26 | 22 | }
|
27 |
| - |
28 |
| - pq.offer(new Element(temp.idx+1, temp.x, nums1[temp.idx+1])); |
29 |
| - } |
30 |
| - |
31 |
| - return ans; |
32 |
| - } |
33 |
| - |
34 |
| - class Element { |
35 |
| - int idx; |
36 |
| - int x; |
37 |
| - int y; |
38 |
| - |
39 |
| - public Element(int val, int x, int y) { |
40 |
| - this.idx = val; |
41 |
| - this.x = x; |
42 |
| - this.y = y; |
43 |
| - } |
44 |
| - |
45 |
| - @Override |
46 |
| - public String toString() { |
47 |
| - return "Element{" + |
48 |
| - "idx=" + idx + |
49 |
| - ", x=" + x + |
50 |
| - ", y=" + y + |
51 |
| - '}'; |
52 | 23 | }
|
| 24 | + return result; |
53 | 25 | }
|
54 | 26 | }
|
0 commit comments