A Swift Solution


  • 0
    T
    func intersect(nums1: [Int], _ nums2: [Int]) -> [Int] {
            
            if nums1.count == 0 || nums2.count == 0 {
                return nums1.count == 0 ? nums1 : nums2
            }
            
            var numCount1:[Int:Int] = [:]
            var numCount2:[Int:Int] = [:]
            countNum(nums1, &numCount1)
            countNum(nums2, &numCount2)
            let interNums = [Int](Set<Int>(nums1).intersect(nums2))
            var result:[Int] = []
            for inter in interNums {
                if numCount1[inter] != nil && numCount2[inter] != nil {
                    for i in 0..<min(numCount1[inter]!,numCount2[inter]!){
                        result.append(inter)
                    }
                }
            }
            return result
        }
        
        func countNum(nums: [Int], inout _ numCount: [Int:Int]){
            for num in nums {
                if numCount[num] == nil {
                    numCount[num] = 1
                }else {
                    numCount[num] = numCount[num]! + 1
                }
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.