zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    jsp中上传图片(使用ajaxfileupload)
    快慢的悖论
    为什么所有的架构都是糟糕的
    软件项目是这样失败的。
    初识微信小程序
    Hibernate hql getHibernateTemplate()常用方法汇总
    JAVA中关于set()和get()方法的理解及使用
    java性能调优实战
    PLSQL显示乱码-无法进行中文条件查询解决
    Oracle 10g bigfile表空间简介
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/11581886.html
Copyright © 2011-2022 走看看