Skip to content

Commit ac7d4b1

Browse files
committed
349. Intersection of Two Arrays
1 parent f0ab86d commit ac7d4b1

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,6 @@ Not only Leetcode solutions in Swift.
1717
* [217. Contains Duplicate](https://leetcode.com/problems/contains-duplicate/)
1818
* [219. Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/)
1919
* [259. 3Sum Smaller](https://leetcode.com/problems/3sum-smaller)
20+
* [349. Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/)
2021
* [454. 4Sum II](https://leetcode.com/problems/4sum-ii/)
2122
* [475. Heaters](https://leetcode.com/problems/heaters/?tab=Description)

SwiftyLeetCode.playground/Contents.swift

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ extension Solution {
2020

2121
for i in 0 ..< nums.count {
2222
if let value = map[nums[i]] {
23-
return [value + 1, i + 1]
23+
return [value, i]
2424
}
2525

2626
map[target - nums[i]] = i
@@ -589,6 +589,54 @@ let threeSumSmallerNums = [-2, 0, 1, 3]
589589
let threeSumSmallerTarget = 2
590590
Solution.threeSumSmaller(nums: threeSumSmallerNums, threeSumSmallerTarget)
591591

592+
/**
593+
* 349. Intersection of Two Arrays
594+
* https://leetcode.com/problems/intersection-of-two-arrays/
595+
*/
596+
597+
extension Solution {
598+
class func intersection(nums1: [Int]?, nums2: [Int]?) -> [Int]? {
599+
guard let nums1 = nums1, let nums2 = nums2 else { return nil }
600+
601+
let sortedNums2 = nums2.sorted()
602+
var set = Set<Int>()
603+
604+
for num in nums1 {
605+
if set.contains(num) {
606+
continue
607+
}
608+
609+
if let _ = binarySearch(sortedNums2, key: num) {
610+
set.insert(num)
611+
}
612+
}
613+
614+
return Array(set)
615+
}
616+
617+
// From Swift Algorithm Club (https://github.com/raywenderlich/swift-algorithm-club/blob/master/Binary%20Search)
618+
class func binarySearch<T: Comparable>(_ a: [T], key: T) -> Int? {
619+
var lowerBound = 0
620+
var upperBound = a.count
621+
while lowerBound < upperBound {
622+
let midIndex = lowerBound + (upperBound - lowerBound) / 2
623+
if a[midIndex] == key {
624+
return midIndex
625+
} else if a[midIndex] < key {
626+
lowerBound = midIndex + 1
627+
} else {
628+
upperBound = midIndex
629+
}
630+
}
631+
return nil
632+
}
633+
}
634+
635+
// usage
636+
let intersectionNums1 = [1, 2, 2, 1]
637+
let intersectionNums2 = [2, 2]
638+
Solution.intersection(nums1: intersectionNums1, nums2: intersectionNums2)
639+
592640
/**
593641
* 454. 4Sum II
594642
* https://leetcode.com/problems/4sum-ii/

0 commit comments

Comments
 (0)