Implement a data structure supporting the following operations:
- Inc(Key) - Inserts a new key with value 1. Or increments an existing key by 1. Key is guaranteed to be a non-empty string.
- Dec(Key) - If Key's value is 1, remove it from the data structure. Otherwise decrements an existing key by 1. If the key does not exist, this function does nothing. Key is guaranteed to be a non-empty string.
- GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string
""
. - GetMinKey() - Returns one of the keys with minimal value. If no element exists, return an empty string
""
.
Challenge: Perform all these in O(1) time complexity.
解题思路:
插入删除能在O(1)时间完成的也就hash table了。所以用unordered_map<string , int>存储每个字符串对应的频次。因为需要根据频次返回最大频次和最小频次对应的字符串,所以用map<int , set<string>> 存储对应频次的所有字符串,因为map是根据key有序排列的,所以map的第一个和最后一个key分别是最小频次和最大频次;
class AllOne {
public:
/** Initialize your data structure here. */
AllOne() {
}
/** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
void inc(string key)
{
if(keys.count(key))
{
fre[keys[key]].erase(key) ;
if(fre[keys[key]].empty()) fre.erase(keys[key]) ;
}
keys[key]++ ;
fre[keys[key]].insert(key) ;
}
/** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
void dec(string key)
{
if(!keys.count(key)) return ;
fre[keys[key]].erase(key) ;
if(fre[keys[key]].empty()) fre.erase(keys[key]) ;
if(--keys[key] == 0)
{
keys.erase(key) ;
}
else
{
fre[keys[key]].insert(key) ;
}
}
/** Returns one of the keys with maximal value. */
string getMaxKey()
{
if(fre.empty()) return "" ;
int n = fre.size() ;
cout<<fre.begin()->first<<endl;
return *((next(fre.begin() , n - 1)->second).begin()) ;
}
/** Returns one of the keys with Minimal value. */
string getMinKey() {
if(fre.empty()) return "" ;
return *((fre.begin()->second).begin()) ;
}
private :
unordered_map<string , int> keys ;
map<int , set<string>> fre ;
};
/**
* Your AllOne object will be instantiated and called as such:
* AllOne* obj = new AllOne();
* obj->inc(key);
* obj->dec(key);
* string param_3 = obj->getMaxKey();
* string param_4 = obj->getMinKey();
*/