Here my code:
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
}
}
}
I tried decreasing the "key" in "Line1" but not getting correct output. Sample Input:
size1: 6
array1: 2 6 8 5 4 3
size2: 7
array2: 2 2 3 4 7 4 3
Your Output: 2 2 3 4 4 3
Expected Output: 2 3 4
Underlying logic is correct, but syntax is wrong:
mymap.count(x)
returns the number of time key is present. You want mymap[x]
(or use a std::multi_set
).
Line1 should then be:
mymap[input2[i]]--;
In addition, your first loop (which has similar error BTW) can be simplified to:
std::unordered_map<int,int> mymap;
for(int i=0;i<size1;i++){
mymap[input1[i]]++;
}
So final code:
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]]--;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.