File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments