Add two versions of intersection function in Go

This commit is contained in:
tlylt
2024-01-23 07:41:36 +08:00
parent f1c54e67c0
commit d8f076ef51

View File

@ -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