Back to Leetcode Go

349. Intersection of Two Arrays

website/content.en/ChapterFour/0300~0399/0349.Intersection-of-Two-Arrays.md

1.7.971.1 KB
Original Source

349. Intersection of Two Arrays

Problem

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.

Problem Summary

Find the intersection elements of two arrays. If the same number appears multiple times among the intersection elements, output it only once.

Solution Approach

Store every number in the first array in a map, then iterate through the second array and check whether it exists in the map. If it exists, delete it from the map (because the output requirement is to output it only once).

Code

go

package leetcode

func intersection(nums1 []int, nums2 []int) []int {
	m := map[int]bool{}
	var res []int
	for _, n := range nums1 {
		m[n] = true
	}
	for _, n := range nums2 {
		if m[n] {
			delete(m, n)
			res = append(res, n)
		}
	}
	return res
}