mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 13:00:22 +08:00
更新 0349.两个数组的交集 go版本(利用set,不用统计次数,减少空间复杂度)
更新 0349.两个数组的交集 go版本(利用set,不用统计次数,减少空间复杂度)
This commit is contained in:
@ -143,6 +143,26 @@ func intersection(nums1 []int, nums2 []int) []int {
|
||||
return res
|
||||
}
|
||||
```
|
||||
```golang
|
||||
//优化版,利用set,减少count统计
|
||||
func intersection(nums1 []int, nums2 []int) []int {
|
||||
set:=make(map[int]struct{},0)
|
||||
res:=make([]int,0)
|
||||
for _,v:=range nums1{
|
||||
if _,ok:=set[v];!ok{
|
||||
set[v]=struct{}{}
|
||||
}
|
||||
}
|
||||
for _,v:=range nums2{
|
||||
//如果存在于上一个数组中,则加入结果集,并清空该set值
|
||||
if _,ok:=set[v];ok{
|
||||
res=append(res,v)
|
||||
delete(set, v)
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
javaScript:
|
||||
|
||||
|
Reference in New Issue
Block a user