LeetCode 373. Find K Pairs with Smallest Sums

本文涉及的产品
模型在线服务 PAI-EAS,A10/V100等 500元 1个月
交互式建模 PAI-DSW,每月250计算时 3个月
模型训练 PAI-DLC,100CU*H 3个月
简介: 给定两个以升序排列的整形数组 nums1 和 nums2, 以及一个整数 k。定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2。找到和最小的 k 对数字 (u1,v1), (u2,v2) ... (uk,vk)。

v2-64f6d62f3e95cb3a2596ad2bf7e41c86_1440w.jpg

Description



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]


描述



给定两个以升序排列的整形数组 nums1 和 nums2, 以及一个整数 k。

定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2。


找到和最小的 k 对数字 (u1,v1), (u2,v2) ... (uk,vk)。


示例 1:


输入: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
输出: [1,2],[1,4],[1,6]
解释: 返回序列中的前 3 对数:
     [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]


示例 2:


输入: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
输出: [1,1],[1,1]
解释: 返回序列中的前 2 对数:
     [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]

示例 3:


输入: nums1 = [1,2], nums2 = [3], k = 3 
输出: [1,3],[2,3]
解释: 也可能序列中所有的数对都被返回:[1,3],[2,3]


思路


  • 使用小顶堆。
  • 首先将 nums1 的第一个数和 nums2 的前 k 个数组合,并存入索引,构成(nums1[0]+nums[i],0,i)结构,存入堆中。
  • 每次从堆中取出最小元素对,假定此时的最小元素对由 nums1[i] 和 nums2[j] 构成;由于我们已经 nums2 中的前 k 个元素压入了堆中, 那么在 nums1 和 nums2 剩下的元素中,大于元素对 (nums1[i] + nums2[j],i,j) 的最小元素对就是 (nums1[i+1] + nums2[j],i+1,j),我们将此压入堆中。
  • 重复上面的步骤直到取出了 k 个元素对(或者堆空)。


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-06-28 10:56:10
# @Last Modified by:   何睿
# @Last Modified time: 2019-06-28 11:40:14
from heapq import heappop, heappush
class Solution:
    def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
        # 处理异常情况
        if not nums1 or not nums2:return []
        heap = list()
        len1, len2 = len(nums1), len(nums2)
        # k 对最小数对的和,所有的数一定都落在 nums1 和 nums2 的前 k 个数中
        num = k if len2 > k else len2
        # 将第一个数组的第一个数与第二个数组的前 k 个数组合
        for i in range(num):
            heappush(heap, (nums1[0]+nums2[i], 0, i))
        count = 0
        res = list()
        # 取 k 个有效数对
        while heap and count < k:
            # 最小数对是 (nums1[i], nums2[j])
            _sum, i, j = heappop(heap)
            res.append([nums1[i], nums2[j]])
            count += 1
            if i + 1 < len1:
                # 取到了最小数对 (nums1[i], nums2[j])
                # 我们将比最小数对大的最小数对 (nums1[i+1], nums2[j]) 压入堆中
                heappush(heap, (nums1[i + 1] + nums2[j], i + 1, j))
        del heap
        return res

源代码文件在 这里


相关实践学习
使用PAI-EAS一键部署ChatGLM及LangChain应用
本场景中主要介绍如何使用模型在线服务(PAI-EAS)部署ChatGLM的AI-Web应用以及启动WebUI进行模型推理,并通过LangChain集成自己的业务数据。
机器学习概览及常见算法
机器学习(Machine Learning, ML)是人工智能的核心,专门研究计算机怎样模拟或实现人类的学习行为,以获取新的知识或技能,重新组织已有的知识结构使之不断改善自身的性能,它是使计算机具有智能的根本途径,其应用遍及人工智能的各个领域。 本课程将带你入门机器学习,掌握机器学习的概念和常用的算法。
目录
相关文章
|
Java
Leetcode 295. Find Median from Data Stream
在一个有序数组中找中位数,但需要支持再数组中添加新的元素。本来是有序里的,可以很轻易就查到中位数,但如果添加新数字后,不一定有序。如果先对数组排序,那代价就比较大了,每次排序时间复杂度O(n*log(n)),看discuss发现了一种很巧妙的解法,可以把添加数据的时间复杂度降低到O(log(n)) ,查询中位数O(1)。
64 0
Leetcode Find Minimum in Rotated Sorted Array 题解
对一个有序数组翻转, 就是随机取前K个数,移动到数组的后面,然后让你找出最小的那个数,注意,K有可能是0,也就是没有翻转。
68 0
|
算法 Python
LeetCode 1160. 拼写单词 Find Words That Can Be Formed by Characters
LeetCode 1160. 拼写单词 Find Words That Can Be Formed by Characters
LeetCode 1160. 拼写单词 Find Words That Can Be Formed by Characters
|
JavaScript 索引
LeetCode 436. Find Right Interval
Given a set of intervals, for each of the interval i, check if there exists an interval j whose start point is bigger than or equal to the end point of the interval i, which can be called that j is on the "right" of i.
91 0
LeetCode 436. Find Right Interval
LeetCode 389. Find the Difference
给定两个字符串 s 和 t,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。 请找出在 t 中被添加的字母。
132 0
LeetCode 389. Find the Difference
|
算法 Python
LeetCode 295. Find Median from Data Stream
中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。
117 0
LeetCode 295. Find Median from Data Stream
|
索引
LeetCode 287. Find the Duplicate Number
给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。
95 0
LeetCode 287. Find the Duplicate Number
|
索引
LeetCode 162. Find Peak Element
给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。
113 0
LeetCode 162. Find Peak Element
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
|
5月前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行

热门文章

最新文章