File tree 1 file changed +13
-3
lines changed
1 file changed +13
-3
lines changed Original file line number Diff line number Diff line change 1
1
/**
2
2
* Question Link: https://leetcode.com/problems/intersection-of-two-arrays/
3
- * Primary idea: Use set interact function to help
3
+ * Primary idea: Use set to hold numbers for one array and iterate the other one to output result,
4
+ * remove the number from set to avoid duplicates.
5
+ *
6
+ * Note: Do not use built-in intersection function for Set in Swift, that is not this question is asking for.
4
7
*
5
8
* Time Complexity: O(n), Space Complexity: O(n)
6
9
*
7
10
*/
8
11
9
12
class IntersectionTwoArrays {
10
- func intersection( nums1: [ Int ] , _ nums2: [ Int ] ) -> [ Int ] {
11
- return Array ( Set ( nums1) . intersection ( Set ( nums2) ) )
13
+ func intersection( _ nums1: [ Int ] , _ nums2: [ Int ] ) -> [ Int ] {
14
+ var set = Set ( nums1) , res = [ Int] ( )
15
+
16
+ for num in nums2 where set. contains ( num) {
17
+ res. append ( num)
18
+ set. remove ( num)
19
+ }
20
+
21
+ return res
12
22
}
13
23
}
You can’t perform that action at this time.
0 commit comments