Intersection of Two Arrays LeetCode solution in C++

1
class Solution {
2
public:
3
// what i think is we have to return the intersection elements from both nums
4
vector<int> intersection(vector<int> &nums1, vector<int> &nums2) {
5
// result vector which will store those values which will be intersecting in
6
// both nums
7
vector<int> result;
8

9
// map intersection, which will store values of all the elements in num1
10
unordered_map<int, int> intersection;
11

12
// map will store all the values of num1(as key),with corresponding value 1
13
for (auto character : nums1) {
14
intersection[character] = 1;
15
}
16

17
// this loop will check if any element of num1 is there in num2? if yes,
18
// insert it in result after inserting it once, make its corresponding value
19
// to 0 so that if you find any elements, that is repeating in num2, as well
20
// as present in num1 so you dont enter it twice in result, you should enter
21
// it once only
22
for (auto character : nums2) {
23
// if found once, it's value would be 1, so entered in result
24
// after it is entered in result, its value we change to 0
25
// so agin if that same element repeats, due to 0 as its value, we avoid
26
// pushing it to result
27
if (intersection[character]) {
28
result.push_back(character);
29
intersection[character] = 0;
30
}
31
}
32

33
// after getting all the intersecting elements,we return result
34
return result;
35
}
36
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0