跳到主要内容

2671.频率跟踪器

链接:2671.频率跟踪器
难度:Medium
标签:设计、哈希表
简介:请你设计并实现一个能够对其中的值进行跟踪的数据结构,并支持对频率相关查询进行应答。

题解 1 - python

  • 编辑时间:2024-03-21
  • 执行用时:374ms
  • 内存消耗:81.89MB
  • 编程语言:python
  • 解法介绍:利用两个dict记录数量和频率。
class FrequencyTracker:
def __init__(self):
self.freq_map = {}
self.cnt_map = {}

def del_freq(self, freq: int, number: int):
if freq in self.freq_map and number in self.freq_map[freq]:
self.freq_map[freq].remove(number)
if not len(self.freq_map[freq]): del self.freq_map[freq]
def add_freq(self, freq: int, number: int):
if freq not in self.freq_map: self.freq_map[freq] = set()
if number not in self.freq_map[freq]: self.freq_map[freq].add(number)
def add(self, number: int) -> None:
if number not in self.cnt_map: self.cnt_map[number] = 0
self.del_freq(self.cnt_map[number], number)
self.cnt_map[number] += 1
self.add_freq(self.cnt_map[number], number)
def deleteOne(self, number: int) -> None:
if number not in self.cnt_map: self.cnt_map[number] = 0
self.del_freq(self.cnt_map[number], number)
if self.cnt_map[number] > 0:
self.cnt_map[number] -= 1
self.add_freq(self.cnt_map[number], number)
def hasFrequency(self, frequency: int) -> bool:
return frequency in self.freq_map