LeetCode/go/intersection-of-two-arrays-ii.go
Matej Focko d89dbdcac2
go: add «350. Intersection of Two Arrays II»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-07-02 15:38:49 +02:00

31 lines
530 B
Go

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
}