当前位置:   article > 正文

双哈希统计,LeetCode 2671. 频率跟踪器

双哈希统计,LeetCode 2671. 频率跟踪器

一、题目

1、题目描述

请你设计并实现一个能够对其中的值进行跟踪的数据结构,并支持对频率相关查询进行应答。

实现 FrequencyTracker 类:

  • FrequencyTracker():使用一个空数组初始化 FrequencyTracker 对象。
  • void add(int number):添加一个 number 到数据结构中。
  • void deleteOne(int number):从数据结构中删除一个 number 。数据结构 可能不包含 number ,在这种情况下不删除任何内容。
  • bool hasFrequency(int frequency): 如果数据结构中存在出现 frequency 次的数字,则返回 true,否则返回 false

2、接口描述

python3
  1. class FrequencyTracker:
  2. def __init__(self):
  3. def add(self, number: int) -> None:
  4. def deleteOne(self, number: int) -> None:
  5. def hasFrequency(self, frequency: int) -> bool:
  6. # Your FrequencyTracker object will be instantiated and called as such:
  7. # obj = FrequencyTracker()
  8. # obj.add(number)
  9. # obj.deleteOne(number)
  10. # param_3 = obj.hasFrequency(frequency)
​cpp
  1. class FrequencyTracker {
  2. public:
  3. FrequencyTracker() {
  4. }
  5. void add(int number) {
  6. }
  7. void deleteOne(int number) {
  8. }
  9. bool hasFrequency(int frequency) {
  10. }
  11. };
  12. /**
  13. * Your FrequencyTracker object will be instantiated and called as such:
  14. * FrequencyTracker* obj = new FrequencyTracker();
  15. * obj->add(number);
  16. * obj->deleteOne(number);
  17. * bool param_3 = obj->hasFrequency(frequency);
  18. */

3、原题链接

2671. 频率跟踪器


二、解题报告

1、思路分析

2、复杂度

时间复杂度: 单词操作O(1)空间复杂度:O(n),n为操作次数

3、代码详解

​python3
  1. class FrequencyTracker:
  2. def __init__(self):
  3. self.cnt = Counter()
  4. self.freq = Counter()
  5. def add(self, number: int, delta = 1) -> None:
  6. self.freq[self.cnt[number]] -= 1
  7. self.cnt[number] += delta
  8. self.freq[self.cnt[number]] += 1
  9. def deleteOne(self, number: int) -> None:
  10. if self.cnt[number]:
  11. self.add(number, -1)
  12. def hasFrequency(self, frequency: int) -> bool:
  13. return self.freq[frequency] > 0
  14. # Your FrequencyTracker object will be instantiated and called as such:
  15. # obj = FrequencyTracker()
  16. # obj.add(number)
  17. # obj.deleteOne(number)
  18. # param_3 = obj.hasFrequency(frequency)
cpp
  1. class FrequencyTracker {
  2. public:
  3. unordered_map<int, int> cnt, freq;
  4. FrequencyTracker() {
  5. }
  6. void add(int number) {
  7. freq[cnt[number]]--, freq[++cnt[number]]++;
  8. }
  9. void deleteOne(int number) {
  10. if(cnt[number])
  11. freq[cnt[number]]--, freq[--cnt[number]]++;
  12. }
  13. bool hasFrequency(int frequency) {
  14. return freq[frequency] > 0;
  15. }
  16. };
  17. /**
  18. * Your FrequencyTracker object will be instantiated and called as such:
  19. * FrequencyTracker* obj = new FrequencyTracker();
  20. * obj->add(number);
  21. * obj->deleteOne(number);
  22. * bool param_3 = obj->hasFrequency(frequency);
  23. */

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号