Skip to content

Commit e2b634d

Browse files
author
Yi Gu
committed
[Array] add Solutions to Intersection of Two Arrays I, II
1 parent d8628e0 commit e2b634d

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

Array/IntersectionTwoArrays.swift

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/intersection-of-two-arrays/
3+
* Primary idea: Use set interact function to help
4+
*
5+
* Time Complexity: O(n), Space Complexity: O(n)
6+
*
7+
*/
8+
9+
class IntersectionTwoArrays {
10+
func intersection(nums1: [Int], _ nums2: [Int]) -> [Int] {
11+
return [Int](Set<Int>(nums1).intersect(nums2))
12+
}
13+
}

Array/IntersectionTwoArraysII.swift

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/intersection-of-two-arrays-ii/
3+
* Primary idea: Sort and iterate to find all common elements
4+
* Note: Set cannot help you to find the number of common elements; thus it is not effective
5+
*
6+
* Time Complexity: O(nlogn), Space Complexity: O(n)
7+
*
8+
*/
9+
10+
class IntersectionTwoArraysII {
11+
func intersect(nums1: [Int], _ nums2: [Int]) -> [Int] {
12+
var nums1 = nums1.sort({$0 < $1})
13+
var nums2 = nums2.sort({$0 < $1})
14+
15+
var i = 0
16+
var j = 0
17+
var res = [Int]()
18+
19+
while i < nums1.count && j < nums2.count {
20+
if nums1[i] < nums2[j] {
21+
i += 1
22+
} else if nums1[i] > nums2[j] {
23+
j += 1
24+
} else {
25+
res.append(nums1[i])
26+
i += 1
27+
j += 1
28+
}
29+
}
30+
31+
return res
32+
}
33+
}

0 commit comments

Comments
 (0)