373. Find K Pairs with Smallest Sums
2017-12-28 15:47
357 查看
1、题目描述
输入两个数组,和一个整数k,由第一个数组的一个元素和第二个数组的一个元素组成的pair中,返回前k个和最小的pair。
2、思路
优先队列保存pair,写比较函数pair和较大的优先。
把队列中的前k个pair当做答案。
3、代码
输入两个数组,和一个整数k,由第一个数组的一个元素和第二个数组的一个元素组成的pair中,返回前k个和最小的pair。
2、思路
优先队列保存pair,写比较函数pair和较大的优先。
把队列中的前k个pair当做答案。
3、代码
struct cmp{ bool operator()(pair<int,int>a,pair<int,int>b){ return a.first+a.second>b.first+b.second; } }; class Solution { public: vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) { priority_queue<pair<int,int>,vector<pair<int,int>>,cmp>q; vector<pair<int, int>>ans; for(int i=0;i<nums1.size()&&i<k;i++){ for(int j=0;j<nums2.size()&&i*j<k;j++){ q.push(make_pair(nums1[i],nums2[j])); } } while(k-- &&!q.empty()){ ans.push_back(q.top()); q.pop(); } return ans; } };
相关文章推荐
- [leetcode-373]Find K Pairs with Smallest Sums(java)
- 373. Find K Pairs with Smallest Sums
- 373. Find K Pairs with Smallest Sums
- [LeetCode] 373. Find K Pairs with Smallest Sums 找和最小的K对数字
- LeetCode[373] Find K Pairs with Smallest Sums
- 373. Find K Pairs with Smallest Sums
- 373. Find K Pairs with Smallest Sums
- 373. Find K Pairs with Smallest Sums
- 373. Find K Pairs with Smallest Sums
- 373. Find K Pairs with Smallest Sums (java,优先队列)
- 373. Find K Pairs with Smallest Sums
- 373. Find K Pairs with Smallest Sums
- Leetcode 373 Find K Pairs with Smallest Sums
- leetcode:heap:Find K Pairs with Smallest Sums(373)
- 373. Find K Pairs with Smallest Sums**
- [Leetcode] 373. Find K Pairs with Smallest Sums 解题报告
- Leetcode373: Find K Pairs with Smallest Sums
- 373. Find K Pairs with Smallest Sums
- leetcode_373 Find K Pairs with Smallest Sums
- 373. Find K Pairs with Smallest Sums