forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Array] add Solutions to Intersection of Two Arrays I, II
- Loading branch information
Yi Gu
committed
Jul 6, 2016
1 parent
d8628e0
commit e2b634d
Showing
2 changed files
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/intersection-of-two-arrays/ | ||
* Primary idea: Use set interact function to help | ||
* | ||
* Time Complexity: O(n), Space Complexity: O(n) | ||
* | ||
*/ | ||
|
||
class IntersectionTwoArrays { | ||
func intersection(nums1: [Int], _ nums2: [Int]) -> [Int] { | ||
return [Int](Set<Int>(nums1).intersect(nums2)) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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 | ||
} | ||
} |