Solution in Go (9ms) using maps


  • 0
    func intersect(nums1 []int, nums2 []int) []int {
        if len(nums1) > len(nums2) { nums1, nums2 = nums2, nums1 }
        nums1Map := make(map[int]int)
        result := []int{}
        for i := 0; i < len(nums1); i++ { nums1Map[nums1[i]]++ }
        for i := 0; i < len(nums2); i++ {
            count, ok := nums1Map[nums2[i]]
            if ok && count != 0 {
                result = append(result, nums2[i])
                nums1Map[nums2[i]]--
            }
        }
        return result
    }
    

Log in to reply
 

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