Skip to content

Commit b383000

Browse files
Add new cpp solution with explanation
1 parent 040ecda commit b383000

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
Intuition
2+
Using hash map to opimize the algorithm o(N). Instead of using sorting. It takes O(NlogN). But my solution takes require more space then sorting approach.
3+
Approach
4+
My first thought is using a "Hash_map" to store the elements of 1 array and corresponding frequency into hash map.
5+
Add the elements of "nums1" into map with corresponding frequency.
6+
Iterate throught each element of "nums2". If frequency of the element stored in hash map greater than 0. We add this element into "res" and decrease the frequency of this element.
7+
Complexity
8+
Time complexity: O(N).
9+
Space complexity: O(N).
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <unordered_map>
4+
#include <algorithm>
5+
using namespace std;
6+
7+
class Solution {
8+
public:
9+
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
10+
vector<int> res;
11+
unordered_map<int, int> box;
12+
for (int num : nums1)
13+
box[num]++;
14+
for (int i = 0; i < nums2.size(); ++i) {
15+
if (box[nums2[i]] > 0) {
16+
res.push_back(nums2[i]);
17+
box[nums2[i]]--;
18+
} else {
19+
continue;
20+
}
21+
}
22+
return res;
23+
}
24+
};

0 commit comments

Comments
 (0)