350. Intersection of Two Arrays II--LeetCode Record

Tong_hdj發表於2016-07-14

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.

class Solution {
    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
            }
        }
    }
}

相關文章