---
# System prepended metadata

title: 2671. Frequency Tracker
tags: [Leetcode, Design, HashMap, Medium]

---

Link: https://leetcode.com/problems/frequency-tracker/ 
## 思路
用一个map记录每个数字出现的次数
另外一个map记录每个freq出现的次数
需要注意的是deleteOne的参数有可能根本不存在
还需要注意我们不需要记录有多少个数字freq是0 即使记录了也没有意义
并且如果一个数字已经count=0了 那么我们就需要把它删掉 否则我们还可以继续delete它
## Code
```python=
class FrequencyTracker:
    count = collections.defaultdict(int)
    freqCnt = collections.defaultdict(int)

    def __init__(self):
        self.count = collections.defaultdict(int)
        self.freqCnt = collections.defaultdict(int)

    def add(self, number: int) -> None:
        oldFreq = self.count[number]
        if oldFreq!=0:
            self.freqCnt[oldFreq]-=1
        self.freqCnt[oldFreq+1]+=1
        self.count[number]+=1

    def deleteOne(self, number: int) -> None:
        if number not in self.count: return
        oldFreq = self.count[number]
        self.freqCnt[oldFreq]-=1
        if oldFreq!=1: self.freqCnt[oldFreq-1]+=1
        self.count[number]-=1
        if self.count[number]==0: del self.count[number]

    def hasFrequency(self, frequency: int) -> bool:
        return self.freqCnt[frequency]!=0
```