Intersection of Two Arrays


#1

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

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

 


#2

Use a map to store values and add the matching values to the result.

func intersection(nums1 []int, nums2 []int) []int {
    result := make([]int, 0)
    if len(nums1)==0 || len(nums2)==0 { return result}
    m := make(map[int]bool)
    for _, num := range nums1{
        m[num] = true
    }
    for _, num := range nums2{
        if m[num]{
            m[num] = false
            result = append(result, num)
        }
    }
    return result
}