@@ -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]
589589let threeSumSmallerTarget = 2
590590Solution . 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