Skip to content

Commit af8723b

Browse files
authored
[Array] Refactor solution to Intersection of Two Arrays
1 parent 62e89a0 commit af8723b

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

Array/IntersectionTwoArrays.swift

+13-3
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,23 @@
11
/**
22
* 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.
47
*
58
* Time Complexity: O(n), Space Complexity: O(n)
69
*
710
*/
811

912
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
1222
}
1323
}

0 commit comments

Comments
 (0)