From d8f076ef514737ff4ad9247a7380ba2f7c8c7515 Mon Sep 17 00:00:00 2001 From: tlylt Date: Tue, 23 Jan 2024 07:41:36 +0800 Subject: [PATCH] Add two versions of intersection function in Go --- problems/0349.两个数组的交集.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 26a9286d..25c4e702 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -210,6 +210,8 @@ class Solution: ### Go: +(版本一)使用字典和集合 + ```go func intersection(nums1 []int, nums2 []int) []int { set:=make(map[int]struct{},0) // 用map模拟set @@ -230,6 +232,28 @@ func intersection(nums1 []int, nums2 []int) []int { } ``` +(版本二)使用数组 + +```go +func intersection(nums1 []int, nums2 []int) []int { + count1 := make([]int, 1001, 1001) + count2 := make([]int, 1001, 1001) + res := make([]int, 0) + for _, v := range nums1 { + count1[v] = 1 + } + for _, v := range nums2 { + count2[v] = 1 + } + for i := 0; i <= 1000; i++ { + if count1[i] + count2[i] == 2 { + res = append(res, i) + } + } + return res +} +``` + ### JavaScript: ```js