From d89dbdcac20c293fe8e31f1611614c31e55aedc9 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 2 Jul 2024 15:38:14 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB350.=20Intersection=20of=20Tw?= =?UTF-8?q?o=20Arrays=20II=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/intersection-of-two-arrays-ii.go | 31 +++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 go/intersection-of-two-arrays-ii.go diff --git a/go/intersection-of-two-arrays-ii.go b/go/intersection-of-two-arrays-ii.go new file mode 100644 index 0000000..7cc2527 --- /dev/null +++ b/go/intersection-of-two-arrays-ii.go @@ -0,0 +1,31 @@ +package main + +func intersect(nums1, nums2 []int) []int { + count := func(nums []int) map[int]int { + freqs := make(map[int]int) + for _, x := range nums { + freqs[x]++ + } + return freqs + } + + freqs1 := count(nums1) + freqs2 := count(nums2) + if len(freqs1) > len(freqs2) { + freqs1, freqs2 = freqs2, freqs1 + } + + intersected := []int{} + for x, count1 := range freqs1 { + count2, found := freqs2[x] + if !found { + continue + } + + for range min(count1, count2) { + intersected = append(intersected, x) + } + } + + return intersected +}