From d51d819060914d89b4eb89bd9a9495e48a10ab22 Mon Sep 17 00:00:00 2001 From: X-shuffle <53906918+X-shuffle@users.noreply.github.com> Date: Thu, 19 Aug 2021 22:02:21 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200349.=E4=B8=A4=E4=B8=AA?= =?UTF-8?q?=E6=95=B0=E7=BB=84=E7=9A=84=E4=BA=A4=E9=9B=86=20go=E7=89=88?= =?UTF-8?q?=E6=9C=AC=EF=BC=88=E5=88=A9=E7=94=A8set=EF=BC=8C=E4=B8=8D?= =?UTF-8?q?=E7=94=A8=E7=BB=9F=E8=AE=A1=E6=AC=A1=E6=95=B0=EF=BC=8C=E5=87=8F?= =?UTF-8?q?=E5=B0=91=E7=A9=BA=E9=97=B4=E5=A4=8D=E6=9D=82=E5=BA=A6=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 更新 0349.两个数组的交集 go版本(利用set,不用统计次数,减少空间复杂度) --- problems/0349.两个数组的交集.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 7489352d..62abf639 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -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: