File tree 2 files changed +48
-10
lines changed
algorithms/cpp/intersectionOfTwoArrays
2 files changed +48
-10
lines changed Original file line number Diff line number Diff line change 1
1
// Source : https://leetcode.com/problems/intersection-of-two-arrays/
2
- // Author : Calinescu Valentin
2
+ // Author : Calinescu Valentin, Hao Chen
3
3
// Date : 2016-05-20
4
4
5
5
/* **************************************************************************************
@@ -48,13 +48,25 @@ class Solution2 {
48
48
}
49
49
};
50
50
51
+ /*
52
+ * This Solution use unordered_map, insert the data into a map is more efficent than set
53
+ */
51
54
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
+ };
60
72
Original file line number Diff line number Diff line change 1
1
// Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/
2
- // Author : Calinescu Valentin
2
+ // Author : Calinescu Valentin, Hao Chen
3
3
// Date : 2016-05-22
4
4
5
5
/* **************************************************************************************
@@ -59,3 +59,29 @@ class Solution { // O(NlogN + MlogM)
59
59
return solution;
60
60
}
61
61
};
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
+ };
You can’t perform that action at this time.
0 commit comments