-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution349.go
More file actions
87 lines (77 loc) · 1.65 KB
/
solution349.go
File metadata and controls
87 lines (77 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package solution349
// ============================================================================
// 349. Intersection of Two Arrays
// URL: https://leetcode.com/problems/intersection-of-two-arrays/
// ============================================================================
/*
goos: linux
goarch: amd64
pkg: GoLeetCode/solutions/349
cpu: 13th Gen Intel(R) Core(TM) i7-13700K
Benchmark_intersectionV2
Benchmark_intersectionV2-24 7600792 154.8 ns/op 56 B/op 3 allocs/op
Benchmark_intersectionV1
Benchmark_intersectionV1-24 6605528 172.7 ns/op 56 B/op 3 allocs/op
PASS
*/
func intersectionV2(nums1 []int, nums2 []int) []int {
m := max(len(nums1), len(nums2))
freq := make(map[int]int, m)
for i := 0; i < len(nums1); i++ {
freq[nums1[i]] = 0
}
for i := 0; i < len(nums2); i++ {
_, ok := freq[nums2[i]]
if ok {
freq[nums2[i]] = 1
}
}
output := make([]int, 0, m)
for k, c := range freq {
if c == 1 {
output = append(output, k)
}
}
return output
}
func intersectionV1(nums1 []int, nums2 []int) []int {
ans := []int{}
m1 := make(map[int]int, len(nums1))
m2 := make(map[int]int, len(nums2))
for i := 0; i < len(nums1); i++ {
val := nums1[i]
_, ok := m1[val]
if !ok {
m1[val] = 1
} else {
m1[val]++
}
}
for i := 0; i < len(nums2); i++ {
val := nums2[i]
_, ok := m2[val]
if !ok {
m2[val] = 1
} else {
m2[val]++
}
}
if len(m1) < len(m2) {
for k := range m1 {
_, ok := m2[k]
if !ok {
continue
}
ans = append(ans, k)
}
} else {
for k := range m2 {
_, ok := m1[k]
if !ok {
continue
}
ans = append(ans, k)
}
}
return ans
}