forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntersectionTwoArraysII.swift
More file actions
33 lines (29 loc) · 900 Bytes
/
IntersectionTwoArraysII.swift
File metadata and controls
33 lines (29 loc) · 900 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Question Link: https://leetcode.com/problems/intersection-of-two-arrays-ii/
* Primary idea: Sort and iterate to find all common elements
* Note: Set cannot help you to find the number of common elements; thus it is not effective
*
* Time Complexity: O(nlogn), Space Complexity: O(n)
*
*/
class IntersectionTwoArraysII {
func intersect(nums1: [Int], _ nums2: [Int]) -> [Int] {
var nums1 = nums1.sort({$0 < $1})
var nums2 = nums2.sort({$0 < $1})
var i = 0
var j = 0
var res = [Int]()
while i < nums1.count && j < nums2.count {
if nums1[i] < nums2[j] {
i += 1
} else if nums1[i] > nums2[j] {
j += 1
} else {
res.append(nums1[i])
i += 1
j += 1
}
}
return res
}
}