2671. 频率跟踪器

频率跟踪器

解法一: 哈希

go
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
type FrequencyTracker struct {
hash1 map[int]int
hash2 map[int]int
}

func Constructor() FrequencyTracker {
return FrequencyTracker{
hash1: make(map[int]int),
hash2: make(map[int]int),
}
}

func (this *FrequencyTracker) Add(number int) {
hash1 := this.hash1
hash2 := this.hash2
if count, exists := hash1[number]; exists {
hash2[count]--
hash2[count+1]++
} else {
hash2[1]++
}
hash1[number]++
}

func (this *FrequencyTracker) DeleteOne(number int) {
hash1 := this.hash1
hash2 := this.hash2
if count := hash1[number]; count != 0 {
hash2[count]--
if count > 1 {
hash2[count-1]++
}
hash1[number]--
}
}

func (this *FrequencyTracker) HasFrequency(frequency int) bool {
hash2 := this.hash2
return hash2[frequency] > 0
}

/**
* Your FrequencyTracker object will be instantiated and called as such:
* obj := Constructor();
* obj.Add(number);
* obj.DeleteOne(number);
* param_3 := obj.HasFrequency(frequency);
*/
作者

wuhunyu

发布于

2024-03-21

更新于

2025-01-15

许可协议