LeetCode 算法題 – Intersection of Two Arrays

本頁內容

編寫一個 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}