Skip to content

Commit 44d5a40

Browse files
committed
Updated an simple solution for two easy problems
1 parent ef4f240 commit 44d5a40

File tree

2 files changed

+48
-10
lines changed

2 files changed

+48
-10
lines changed

algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp

+21-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Source : https://leetcode.com/problems/intersection-of-two-arrays/
2-
// Author : Calinescu Valentin
2+
// Author : Calinescu Valentin, Hao Chen
33
// Date : 2016-05-20
44

55
/***************************************************************************************
@@ -48,13 +48,25 @@ class Solution2 {
4848
}
4949
};
5050

51+
/*
52+
* This Solution use unordered_map, insert the data into a map is more efficent than set
53+
*/
5154

52-
53-
54-
55-
56-
57-
58-
59-
55+
class Solution {
56+
public:
57+
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
58+
unordered_map<int, bool> m;
59+
for (auto n : nums1) {
60+
m[n] = true;
61+
}
62+
vector<int> result;
63+
for (auto n : nums2){
64+
if (m.find(n) != m.end() && m[n] ){
65+
result.push_back(n);
66+
m[n]=false;
67+
}
68+
}
69+
return result;
70+
}
71+
};
6072

algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArraysII.cpp

+27-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/
2-
// Author : Calinescu Valentin
2+
// Author : Calinescu Valentin, Hao Chen
33
// Date : 2016-05-22
44

55
/***************************************************************************************
@@ -59,3 +59,29 @@ class Solution { // O(NlogN + MlogM)
5959
return solution;
6060
}
6161
};
62+
63+
64+
65+
/*
66+
* Just simply use the map can have O(M+N) time complexity.
67+
*
68+
*/
69+
70+
71+
class Solution {
72+
public:
73+
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
74+
unordered_map<int, int> m;
75+
for (auto n: nums1) {
76+
m[n]++;
77+
}
78+
vector<int> result;
79+
for (auto n:nums2){
80+
if (m.find(n) != m.end() && m[n]>0 ){
81+
result.push_back(n);
82+
m[n]--;
83+
}
84+
}
85+
return result;
86+
}
87+
};

0 commit comments

Comments
 (0)