编写一个 function 获取两个数值数组的交集,交集中数值唯一。
原题
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
- Each element in the result must be unique.
- The result can be in any order.
分析
- 数值唯一
- 顺序随意
实现
1func intersection(nums1 []int, nums2 []int) []int {
2 m := make(map[int]bool)
3 for _, num := range nums1 {
4 m[num] = true
5 }
6
7 var v []int
8 for _, num := range nums2 {
9 if m[num] {
10 v = append(v, num)
11 delete(m, num)
12 }
13 }
14
15 return v
16}