373. Find K Pairs with Smallest Sums 找出求和和最小的k组数
[抄題]:
You are given two integer arrays?nums1?and?nums2?sorted in ascending order and an integer?k.
Define a pair?(u,v)?which consists of one element from the first array and one element from the second array.
Find the k pairs?(u1,v1),(u2,v2) ...(uk,vk)?with the smallest sums.
Example 1:
Given nums1 = [1,7,11], nums2 = [2,4,6], k = 3Return: [1,2],[1,4],[1,6]The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]?
Example 2:
Given nums1 = [1,1,2], nums2 = [1,2,3], k = 2Return: [1,1],[1,1]The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]?
Example 3:
Given nums1 = [1,2], nums2 = [3], k = 3 Return: [1,3],[2,3]All possible pairs are returned from the sequence: [1,3],[2,3]?[暴力解法]:
每個搜索一遍
時間分析:n^2
空間分析:
?[優化后]:
時間分析:n
空間分析:
[奇葩輸出條件]:
[奇葩corner case]:
[思維問題]:
[英文數據結構或算法,為什么不用別的數據結構或算法]:
?
?
[一句話思路]:
因為第一列的值都可能是最小的,所以先加第一列, 然后用q做bfs
[輸入量]:空:?正常情況:特大:特小:程序里處理到的特殊情況:異常情況(不合法不合理的輸入):
[畫圖]:
?
[一刷]:
?
?
[二刷]:
[三刷]:
[四刷]:
[五刷]:
? [五分鐘肉眼debug的結果]:
[總結]:
bfs的依據是:cur1[0]不變,cur2加一
?
[復雜度]:Time complexity: O(n) Space complexity: O(n)
[算法思想:迭代/遞歸/分治/貪心]:
[關鍵模板化代碼]:
[其他解法]:
[Follow Up]:
[LC給出的題目變變變]:
?[代碼風格] :
?[是否頭一次寫此類driver funcion的代碼] :
?[潛臺詞] :
?
class Solution {public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {//initialiazation: result heapList<int[]> result = new ArrayList<int[]>();PriorityQueue<int[]> q = new PriorityQueue<int[]>((a,b) -> a[0] + a[1] - b[0] - b[1]);//corner casesif (nums1.length == 0 || nums2.length == 0 || k<= 0) return result;//add the first col k nums into qfor (int i = 0; i < nums1.length && i < k; i++) {q.offer(new int[]{nums1[i], nums2[0], 0});}//do bfs under while loop//add the first element to result, expand to other elementswhile (result.size() < k && !q.isEmpty()) {//add the first to resultint[] cur = q.poll();result.add(new int[]{cur[0], cur[1]});//exit when cur[2] exceedsif (cur[2] == nums2.length - 1) continue;//expandq.offer(new int[] {cur[0], nums2[cur[2] + 1], cur[2] + 1});}//returnreturn result;} } View Code?
轉載于:https://www.cnblogs.com/immiao0319/p/9527595.html
總結
以上是生活随笔為你收集整理的373. Find K Pairs with Smallest Sums 找出求和和最小的k组数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 珍惜相聚,亦珍惜离别
- 下一篇: Splay(单点修改+查询)