[Golang] Leetcode - 349. Intersection of two arrays (hash table)

[Golang] Leetcode - 349. Intersection of two arrays (hash table)

Question : Given two arrays nums1 and nums2, return their intersection. Each element in the output must be unique . We can ignore the order of the output results .

Link : Leetcode Leetcode - 349. Intersection of two arrays .

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Explanation: [4,9] is also passable

Idea: My idea is to represent nums1 and nums2 with hash tables a and b, and then traverse a and b, if key1 in a is equal to key2, add the key to the output res, and jump out of the loop, so The advantage is that there will be no repeated numbers in the output res.

Go code:

package main

import "fmt"

func intersection(nums1 []int, nums2 []int) []int {
    
    
	// 用一个map来存储数字以及出现的次数
	a := make(map[int]int)
	b := make(map[int]int)
	for _, v := range nums1 {
    
    
		a[v]++
	}
	for _, v := range nums2 {
    
    
		b[v]++
	}
	// 定义存储最后结果的数组
	var res []int

	for k1 := range a {
    
    
		for k2 := range b {
    
    
			if k1 == k2 {
    
    
				res = append(res, k1)
				break
			}
		}
	}
	return res
}

func main() {
    
    
	nums1 := []int{
    
    1, 2, 2, 1}
	nums2 := []int{
    
    2, 2}
	fmt.Print(intersection(nums1, nums2))
}

Submit a screenshot:
Please add a picture description

Guess you like

Origin blog.csdn.net/a6661314/article/details/124937203