373. 查詢和最小的K對數字
阿新 • • 發佈:2021-12-16
給定兩個以升序排列的整數陣列 nums1 和 nums2,以及一個整數 k。
定義一對值(u,v),其中第一個元素來自nums1,第二個元素來自 nums2。
請找到和最小的 k個數對(u1,v1), (u2,v2) ... (uk,vk)。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/find-k-pairs-with-smallest-sums
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
心之所向,素履以往 生如逆旅,一葦以航import java.util.*; class Solution { private int hash(int x, int y) { return (x + 1) * 100000 + y; } public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) { Set<Integer> visited = new HashSet<>(); List<List<Integer>> ret = new ArrayList<>(); PriorityQueue<int[]> queue = new PriorityQueue<>(new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return Integer.compare(nums1[o1[0]] + nums2[o1[1]], nums1[o2[0]] + nums2[o2[1]]); } }); queue.offer(new int[]{0, 0}); visited.add(hash(0, 0)); while (k-- > 0 && !queue.isEmpty()) { int[] node = queue.poll(); int x = node[0], y = node[1]; ret.add(Arrays.asList(nums1[x], nums2[y])); if (x + 1 < nums1.length && !visited.contains(hash(x + 1, y))) { visited.add(hash(x + 1, y)); queue.offer(new int[]{x + 1, y}); } if (y + 1 < nums2.length && !visited.contains(hash(x, y + 1))) { visited.add(hash(x, y + 1)); queue.offer(new int[]{x, y + 1}); } } return ret; } }