美文网首页LeetCode By Go
[LeetCode By Go 55]350. Intersec

[LeetCode By Go 55]350. Intersec

作者: miltonsun | 来源:发表于2017-08-23 16:13 被阅读6次

    题目

    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)
        }
    }
    

    相关文章

      网友评论

        本文标题:[LeetCode By Go 55]350. Intersec

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