• LeetCode-373 Find K Pairs with Smallest Sums


    题目描述

    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.

    题目大意

    从两个给定的整数数组中依次取出两个数字求和,求能够取出的前k小的数对的和,将数对存入结果当中。

    示例

    E1

    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]

    E2

    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]

    E3

    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]

    解题思路

    简单利用数据结构 map<int, set<pair<int,int>>> ,遍历所有的数对可能性,取出前k个作为结果即可(map会自动按照第一个主参数排序)。

    复杂度分析

    时间复杂度:O(M * N)

    空间复杂度:O(M * N)

    代码

    class Solution {
    public:
        vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
            map<int, multiset<pair<int, int> > > pairSum;
            // 遍历所有可能的数对,保存数对以及它们的和
            for(int j = 0; j < nums2.size(); ++j) {
                for(int i = 0; i < nums1.size(); ++i) {
                    pairSum[nums1[i] + nums2[j]].insert(make_pair(nums1[i], nums2[j]));
                }
            }
            
            vector<vector<int> > res;
            // 取出上述保存的前k个数对
            for(auto iter = pairSum.begin(); iter != pairSum.end(); ++iter) {
                for(auto it = iter->second.begin(); it != iter->second.end(); ++it) {
                    if(res.size() >= k)
                        break;
                    vector<int> tmp;
                    tmp.push_back(it->first);
                    tmp.push_back(it->second);
                    res.push_back(tmp);
                }
                if(res.size() >= k)
                    break;
            }
            
            return res;
        }
    };
  • 相关阅读:
    几个常用排序的代码实现堆排序|快排|归并排序 Marathon
    0647回文子串 Marathon
    任意输入一个日期输出是当年的第几天星期几
    从输入URL到浏览器显示页面发生了什么
    常用链接整理
    computed 与 method
    将博客搬至CSDN
    leetcode_Two Sum
    VC++6.0与Office2010冲突解决方案
    C&C++_malloc函数
  • 原文地址:https://www.cnblogs.com/heyn1/p/11249651.html
Copyright © 2020-2023  润新知