Solution record: Likoujianzhi Offer II 061. and the smallest k number pairs

Given two arrays of integers in ascending order nums1and , and an integer . nums2 k 

Defines a pair of values  (u,v)​​where the first element is from  nums1and the second element is from nums2 .

Please find the smallest number of k pairs with  (u1,v1),  (u2,v2)  ...   (uk,vk) .

Example 1:

Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
 Output: [1,2],[1,4],[1,6]
 Explanation: Return the sequence First 3 logarithms: 
    [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: Returns the first 2 logarithms in 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: It is also possible that all pairs in the sequence are returned: [1,3 ],[2,3]

Idea: Create the largest heap. When the length of the heap is greater than k, pop it out, and the one remaining in the heap is the smallest.

Note: You cannot directly create a large heap, so add a negative sign to the element each time you push (that is, take the opposite number), at this time the minimum value becomes the maximum value, and vice versa.

class Solution:
    def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
        #  当堆中的元素大于k个时,弹出堆顶的最大元素。 最后堆中剩下的k个元素即为最小的k个数对。 
        q = []
        n = 0
        nums1.sort()
        nums2.sort()
        for a in nums1[:k]:
            for b in nums2[:k]:
                heapq.heappush(q , (-a-b , [a,b])) 
        # 这个堆排序都是从小到大,如果是a+b,且堆进行弹出,弹出的都是队列的头部,最后保留的都是队尾元素,此时保留的是最大的k个组合。但如果是-a-b,则余下的是最小的k个组合
        # print(q)
                if len(q) > k:
                    heapq.heappop(q)
        return [a[1] for a in q]

Guess you like

Origin blog.csdn.net/weixin_45314061/article/details/130877117