LeetCode/go/intersection-of-two-arrays-ii.go

32 lines
530 B
Go
Raw Normal View History

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
}