349. 两个数组的交集

349. 两个数组的交集 #

题目地址 #

解题思路 #

TODO

具体实现 #

package main

import "fmt"

func intersection(nums1 []int, nums2 []int) []int {
	if len(nums1) == 0 || len(nums2) == 0 {
		return []int{}
	}

	var (
		set = make(map[int]struct{}, 0)
		ret = make([]int, 0)
	)

	// 重复的会直接覆盖
	for _, each := range nums1 {
		set[each] = struct{}{}
	}

	for _, each := range nums2 {
		if _, ok := set[each]; ok {
			ret = append(ret, each)
			delete(set, each)
		}
	}

	return ret
}

func main() {
	fmt.Println(intersection([]int{1, 2, 2, 1}, []int{2, 2}))
}