Skip to content

Commit

Permalink
Merge pull request soapyigu#78 from soapyigu/Array
Browse files Browse the repository at this point in the history
[Array] add Solutions to Intersection of Two Arrays I, II
  • Loading branch information
soapyigu authored Jul 6, 2016
2 parents 566ab76 + e2b634d commit 258c391
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Array/IntersectionTwoArrays.swift
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))
}
}
33 changes: 33 additions & 0 deletions Array/IntersectionTwoArraysII.swift
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
}
}

0 comments on commit 258c391

Please sign in to comment.