[LeetCode By Go 55]350. Intersection of Two Arrays II

題目

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

解題思路

  1. 遍歷其中一個nums,將元素和其出現的次數放入map
  2. 再遍歷另一個nums,如果元素存在,則將元素append進結果數組ret中,并將map中出現次數-1

Follow up:

  • 如果數組是排好序的,可以一次遍歷兩個數組找到相交元素
  • 一個數組小于另一個數組,可以將較小的數組放入map中
  • 磁盤方案沒考慮

代碼

Intersect.go

package _350_Intersection_Two_Arrays_II

import "fmt"

func Intersect(nums1 []int, nums2 []int) []int {
    len1 := len(nums1)
    len2 := len(nums2)

    var numsShort []int
    var numsLong []int
    if len1 < len2 {
        numsShort = nums1
        numsLong = nums2
    } else {
        numsShort = nums2
        numsLong = nums1
    }

    fmt.Printf("short:%+v\n, long:%+v\n", numsShort, numsLong)
    var numMap map[int]int
    numMap = make(map[int]int)

    for _, v := range numsShort {
        numMap[v]++
    }

    fmt.Printf("map:%+v\n", numMap)
    var ret []int
    for _, v := range numsLong {
        tmp, ok := numMap[v]
        if ok && tmp > 0 {
            numMap[v]--
            ret = append(ret, v)
        }
    }

    return ret
}

測試

Intersect_test.go

package _350_Intersection_Two_Arrays_II

import "testing"

func TestIntersect(t *testing.T) {
    var tests = []struct{
        input1 []int
        input2 []int
    } {
        {[]int{1}, []int{1}, },
    }

    for _, v := range tests {
        Intersect(v.input1, v.input2)
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容