Skip to content

Commit 112c94b

Browse files
committed
350. Intersection of Two Arrays II
1 parent ac7d4b1 commit 112c94b

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

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

SwiftyLeetCode.playground/Contents.swift

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,10 +633,45 @@ extension Solution {
633633
}
634634

635635
// usage
636+
636637
let intersectionNums1 = [1, 2, 2, 1]
637638
let intersectionNums2 = [2, 2]
638639
Solution.intersection(nums1: intersectionNums1, nums2: intersectionNums2)
639640

641+
/**
642+
* 350. Intersection of Two Arrays II
643+
* https://leetcode.com/problems/intersection-of-two-arrays-ii/
644+
*/
645+
646+
extension Solution {
647+
class func intersectionII(nums1: [Int]?, nums2: [Int]?) -> [Int]? {
648+
guard let nums1 = nums1, let nums2 = nums2 else { return nil }
649+
650+
var map = [Int: Int]()
651+
for num in nums1 {
652+
if let count = map[num] {
653+
map[num] = count + 1
654+
} else {
655+
map[num] = 1
656+
}
657+
}
658+
659+
var res = [Int]()
660+
for num in nums2 {
661+
if let count = map[num], count > 0 {
662+
res.append(num)
663+
map[num] = count - 1
664+
}
665+
}
666+
return res
667+
}
668+
}
669+
670+
// usage
671+
let intersectionIINums1 = [1, 2, 2, 1]
672+
let intersectionIINums2 = [2, 2]
673+
Solution.intersectionII(nums1: intersectionIINums1, nums2: intersectionIINums2)
674+
640675
/**
641676
* 454. 4Sum II
642677
* https://leetcode.com/problems/4sum-ii/

0 commit comments

Comments
 (0)