赞
踩
设计一个频率跟踪器,查询出现的数字和出现的频率。
双哈希表,一个跟踪加入数字,一个跟踪频率。
class FrequencyTracker { unordered_map<int,int> p; unordered_map<int,int> freq; public: FrequencyTracker() { } void add(int number) { // p[number]++ // freq[p[number]]++ if (p.find(number) != p.end()) freq[p[number]]--; p[number]++; freq[p[number]]++; } void deleteOne(int number) { // if p[number] > 0 if ( p[number] > 0) { freq[p[number]]--; p[number]--; if ( p[number] > 0){ freq[p[number]]++; } } } bool hasFrequency(int frequency) { // has freq and freq[f] > 0 return freq.find(frequency) != freq.end() && freq[frequency] != 0; } }; /** * Your FrequencyTracker object will be instantiated and called as such: * FrequencyTracker* obj = new FrequencyTracker(); * obj->add(number); * obj->deleteOne(number); * bool param_3 = obj->hasFrequency(frequency); */
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。