go: add «350. Intersection of Two Arrays II»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
1a015c14b4
commit
d89dbdcac2
1 changed files with 31 additions and 0 deletions
31
go/intersection-of-two-arrays-ii.go
Normal file
31
go/intersection-of-two-arrays-ii.go
Normal file
|
@ -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
|
||||||
|
}
|
Loading…
Reference in a new issue