[LeetCode By Go 32]349. Intersection of Two Arrays

题目

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.

解题思路

  1. 将nums1中的元素放入map[int]bool中,值初始化为false
  2. 遍历nums2,map中存在的元素值置为true
  3. 遍历map,取出值为true的元素
    注意
    第三步遍历map的目的是防止有多个重复的相交元素出现

代码

intersection.go

package _349_Intersection_of_Two_Arrays

func intersection(nums1 []int, nums2 []int) []int {
    var ret []int

    var numMap map[int]bool
    numMap = make(map[int]bool)

    for _, v := range nums1 {
        numMap[v] = false
    }

    for _, v := range nums2 {
        _, ok := numMap[v]
        if ok {
            numMap[v] = true
        }
    }

    for k, v := range numMap {
        if v  {
            ret = append(ret, k)
        }
    }
    return ret
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/9de71844beaf
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞