簡體   English   中英

在 C++ 中找到兩個 arrays 的交集

[英]To find intersection of two arrays in C++

這是我的代碼:

  void intersection(int input1[], int input2[], int size1, int size2) {
    unordered_map<int,int> mymap;
    for(int i=0;i<size1;i++){
        if(!mymap.count(input1[i]))
            mymap[input1[i]] = 1;
        else
            mymap[input1[i]]++;
    }

    for(int i=0; i<size2; i++){
        if(mymap.count(input2[i]) > 0){
            cout<<input2[i]<<endl;
            mymap[input2[i]]--;  //Line1
        }   
    }
}

我嘗試減少“Line1”中的“key”,但沒有得到正確的 output。 樣本輸入:

尺寸1:6

數組1:2 6 8 5 4 3

尺寸2:7

數組2:2 2 3 4 7 4 3

您的 Output:2 2 3 4 4 3

預期 Output:2 3 4

底層邏輯是正確的,但語法是錯誤的:

mymap.count(x)返回 key 存在的次數。 您想要mymap[x] (或使用std::multi_set )。

Line1 應該是:

mymap[input2[i]]--;

此外,您的第一個循環(有類似的錯誤順便說一句)可以簡化為:

std::unordered_map<int,int> mymap;
for(int i=0;i<size1;i++){
    mymap[input1[i]]++;
}

所以最終代碼:

void intersection(int input1[], int input2[], int size1, int size2) {
    std::unordered_map<int,int> mymap;
    for(int i=0;i<size1;i++){
        mymap[input1[i]]++;
    }
    for(int i=0; i<size2; i++){
        if (mymap[input2[i]] > 0){
            cout << input2[i] << endl;
            mymap[input2[i]]--;
        }   
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM