美文网首页LeetCode By Go
[LeetCode By Go 32]349. Intersec

[LeetCode By Go 32]349. Intersec

作者: miltonsun | 来源:发表于2017-08-20 18:43 被阅读3次

题目

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
}

相关文章

网友评论

    本文标题:[LeetCode By Go 32]349. Intersec

    本文链接:https://www.haomeiwen.com/subject/afafdxtx.html