Find K Pairs with Smallest Sums 解答
Posted ireneyanglan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Find K Pairs with Smallest Sums 解答相关的知识,希望对你有一定的参考价值。
Question
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:
Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Output: [[1,2],[1,4],[1,6]]
Explanation: 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:
Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2 Output: [1,1],[1,1] Explanation: 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:
Input: nums1 = [1,2], nums2 = [3], k = 3 Output: [1,3],[2,3] Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]
Solution
这道题的关键在于运用Heap这个数据结构。Heap push的时间复杂度是O(logN) 因此整体的时间复杂度是O(KlogK)
Python里如何自定义comparator? 可以传进去一个triple,第一个元素会被比较。
1 from heapq import heappush, heappop 2 class Solution: 3 def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]: 4 if not nums1 or not nums2: 5 return [] 6 m, n = len(nums1), len(nums2) 7 k = min(k, m * n) 8 heap = [] 9 visited = set() 10 result = [] 11 heappush(heap, (nums1[0] + nums2[0], 0, 0)) 12 visited.add((0, 0)) 13 while len(result) < k: 14 val = heappop(heap) 15 i, j = val[1], val[2] 16 result.append([nums1[i], nums2[j]]) 17 if i + 1 < m and (i + 1, j) not in visited: 18 heappush(heap, (nums1[i + 1] + nums2[j], i + 1, j)) 19 visited.add((i + 1, j)) 20 if j + 1 < n and (i, j + 1) not in visited: 21 heappush(heap, (nums1[i] + nums2[j + 1], i, j + 1)) 22 visited.add((i, j + 1)) 23 return result
以上是关于Find K Pairs with Smallest Sums 解答的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 373. Find K Pairs with Smallest Sums
373. Find K Pairs with Smallest Sums
Find K Pairs with Smallest Sums
373. Find K Pairs with Smallest Sums