leetcode 373. Find K Pairs with Smallest Sums 暴力循环求解

蔚落 2022-06-07 02:47 251阅读 0赞

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:
Given nums1 = [1,7,11], nums2 = [2,4,6], k = 3

Return: [1,2],[1,4],[1,6]

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:
Given nums1 = [1,1,2], nums2 = [1,2,3], k = 2

Return: [1,1],[1,1]

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:
Given nums1 = [1,2], nums2 = [3], k = 3

Return: [1,3],[2,3]

All possible pairs are returned from the sequence:
[1,3],[2,3]

直接暴力实现吧,反正Accept了。

代码如下:

  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.Comparator;
  4. import java.util.List;
  5. /*
  6. * 直接暴力去做把,我这里使用的是排序,也可以使用堆
  7. * */
  8. class Solution
  9. {
  10. public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k)
  11. {
  12. List<int[]> res=new ArrayList<>();
  13. List<int[]> all=new ArrayList<>();
  14. for(int i=0;i<nums1.length;i++)
  15. {
  16. for(int j=0;j<nums2.length;j++)
  17. {
  18. all.add(new int[]{nums1[i] , nums2[j]});
  19. }
  20. }
  21. Collections.sort(all, new Comparator<int[]>() {
  22. @Override
  23. public int compare(int[] a, int[] b) {
  24. return (a[0]+a[1])-(b[0]+b[1]);
  25. }
  26. });
  27. if(k<all.size())
  28. {
  29. for(int i =0;i<k;i++)
  30. res.add(all.get(i));
  31. }else
  32. res.addAll(all);
  33. return res;
  34. }
  35. }

下面是C++的做法,直接暴力然后排序即可

我们也可以使用multimap来做,思路是我们将数组对之和作为key存入multimap中,利用其自动排序的机制,这样我们就可以省去sort的步骤,最后把前k个存入res中即可。

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <unordered_map>
  5. #include <set>
  6. #include <unordered_set>
  7. #include <queue>
  8. #include <stack>
  9. #include <string>
  10. #include <climits>
  11. #include <algorithm>
  12. #include <sstream>
  13. #include <functional>
  14. #include <bitset>
  15. #include <numeric>
  16. #include <cmath>
  17. #include <regex>
  18. using namespace std;
  19. bool cmp(pair<int, int> &a, pair<int, int> &b)
  20. {
  21. return a.first + a.second < b.first + b.second;
  22. }
  23. class Solution
  24. {
  25. public:
  26. vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k)
  27. {
  28. vector<pair<int, int>> all;
  29. for (int i = 0; i < min(k,(int)nums1.size()); i++)
  30. {
  31. for (int j = 0; j < min(k, (int)nums2.size()); j++)
  32. {
  33. all.push_back({nums1[i],nums2[j]});
  34. }
  35. }
  36. sort(all.begin(), all.end(), cmp);
  37. while (all.size() > k)
  38. all.pop_back();
  39. return all;
  40. }
  41. };

发表评论

表情:
评论列表 (有 0 条评论,251人围观)

还没有评论,来说两句吧...

相关阅读