C++ 中的兩個陣列的交集


假設我們有兩個陣列,我們必須找到它們的交集。

所以,如果輸入類似於 [1,5,3,6,9],[2,8,9,6,7],則輸出將為 [9,6]

為了解決這個問題,我們將遵循以下步驟——

  • 定義兩個對映 mp1、mp2

  • 定義一個數組 res

  • 對於 x 中的 nums1

    • (將 mp1[x] 增加 1)

  • 對於 x 中的 nums2

    • (將 mp2[x] 增加 1)

  • 對於 mp1 中的每個鍵值對 x

    • cnt := 0

    • cnt := x 的值和 mp2[x 的鍵] 的最小值

    • 如果 cnt > 0,則——

      • 在 res 的末尾插入 x 的鍵

  • 返回 res

示例 

讓我們檢視以下實現以獲得更好的理解——

 即時演示

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<int> intersection(vector<int>& nums1, vector<int>& nums2){
      unordered_map<int, int> mp1, mp2;
      vector<int> res;
      for (auto x : nums1)
         mp1[x]++;
      for (auto x : nums2)
         mp2[x]++;
      for (auto x : mp1) {
         int cnt = 0;
         cnt = min(x.second, mp2[x.first]);
         if (cnt > 0)
            res.push_back(x.first);
         }
         return res;
      }
};
main(){
   Solution ob;
   vector<int> v = {1,5,3,6,9}, v1 = {2,8,9,6,7};
   print_vector(ob.intersection(v, v1));
}

輸入

{1,5,3,6,9},{2,8,9,6,7}

輸出

[9, 6, ]

更新於: 2020-06-10

2K+ 次瀏覽

開啟您的 職業生涯

透過完成課程來獲得認證

開始學習
廣告
© . All rights reserved.