Skip to content

Commit

Permalink
[Array] Refactor solution to Intersection of Two Arrays II
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu authored Aug 6, 2019
1 parent 2adc4c2 commit b144b76
Showing 1 changed file with 4 additions and 8 deletions.
12 changes: 4 additions & 8 deletions Array/IntersectionTwoArraysII.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,16 @@

class IntersectionTwoArraysII {
func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
var frequencies = Dictionary(nums1.map { ($0, 1) } , uniquingKeysWith: +)
var numsFreq = Dictionary(nums1.map { ($0, 1) }, uniquingKeysWith: +)
var res = [Int]()

for num in nums2 {
guard let frequent = frequencies[num] else {
continue
}

if frequent > 0 {
frequencies[num]! = frequent - 1
if let freq = numsFreq[num], freq > 0 {
res.append(num)
numsFreq[num] = freq - 1
}
}

return res
}
}
}

0 comments on commit b144b76

Please sign in to comment.