Intersection of Two Arrays II

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

Solution in Go

func intersect(nums1 []int, nums2 []int) []int {
    intersection := make([]int, 0)
    nums := make(map[int]int)
    
    for _, n := range nums1 {
        nums[n]++
    }

    for _, n := range nums2 {
        _, contains := nums[n]
        if contains {
            intersection = append(intersection, n)
            nums[n]--
            
            if nums[n] == 0 {
                delete(nums, n)
            }
        }
    }
    
    return intersection
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.