1. ๋ฌธ์ : https://leetcode.com/problems/find-k-pairs-with-smallest-sums/description/
2. ํ์ด
pq์ ๋ฃ๋ ๋ฐฉ์์ ์ ์๊ฐํ์ด์ผํ๋ค.
3. ์ฝ๋
class Solution {
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
List<List<Integer>> result = new ArrayList<>();
Queue<int[]> queue = new PriorityQueue<>((a, b) -> (a[0] + a[1] - b[0] - b[1]));
for (int idx = 0; idx < nums1.length && idx < k; idx++) {
queue.offer(new int[] { nums1[idx], nums2[0], 0 });
}
while (k-- > 0 && !queue.isEmpty()) {
int[] curr = queue.poll();
List<Integer> temp = new ArrayList<>();
temp.add(curr[0]);
temp.add(curr[1]);
result.add(temp);
if (curr[2] == nums2.length - 1) {
continue;
}
queue.add(new int[] { curr[0], nums2[curr[2] + 1], curr[2] + 1 });
}
return result;
}
}
'๐ป Coding Problems Solving > Stack | Queue' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค] ํธํ ๋์ค (์๋ฐ java) (0) | 2023.12.02 |
---|---|
[LeetCode] Kth Largest Element (0) | 2023.07.15 |
[LeetCode] Add Two Numbers (0) | 2023.07.14 |
[BOJ 1863] ์ค์นด์ด๋ผ์ธ ์ฌ์ด๊ฑฐ (0) | 2023.06.07 |
[BOJ 11000] ๊ฐ์์ค ๋ฐฐ์ (0) | 2023.05.25 |
์ต๊ทผ๋๊ธ