版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
两层的数据结构。node里面保存val和该val对应的字符串。list根据val从小到大排列。map保存一个string到list对应位置的迭代器。
inc:
没有这个string。就向list头部val==1的节点里存入该string
如果有,就在该string后面val=当前val+1的list节点里面加入该string。并从当前list节点里删掉该string
dec
val==1,直接删掉
在当前list节点前面,val==当前val-1的节点里面加入该string。并在当前node里删掉该string。
!注意list一些接口的使用。insert的时候是在指定迭代器的位置这个位置insert。front、back是值。begin、end是迭代器。end是开区间。
class AllOne {
struct Node{
int val;
unordered_set<string> keys;
};
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) {
auto it = m_.find(key);
if(it == m_.end())
{
if(l_.empty() || l_.front().val != 1)
l_.push_front({1, {}});
l_.front().keys.insert(key);
m_[key] = l_.begin();
return ;
}
auto lit = it->second;
auto nit = next(lit);
if(nit == l_.end() || nit->val != lit->val + 1)
nit = l_.insert(nit, {lit->val + 1});
nit->keys.insert(key);
m_[key] = nit;
remove(lit, key);
}
/** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
void dec(string key) {
auto it = m_.find(key);
if(it == m_.end()) return;
auto lit = it->second;
if(lit->val == 1)
m_.erase(key);
else
{
auto pit = prev(lit);
if(lit == l_.begin() || pit->val != lit->val - 1)
pit = l_.insert(lit, {lit->val - 1, {}});
pit->keys.insert(key);
m_[key] = pit;
}
remove(lit, key);
}
void remove(list<Node>::iterator it, string key)
{
it->keys.erase(key);
if(it->keys.empty()) l_.erase(it);
}
/** Returns one of the keys with maximal value. */
string getMaxKey() {
return l_.empty() ? "" : *l_.back().keys.cbegin();
}
/** Returns one of the keys with Minimal value. */
string getMinKey() {
return l_.empty() ? "" : *l_.front().keys.cbegin();
}
list<Node> l_;
unordered_map<string, list<Node>::iterator> m_;
};
/**
* 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();
*/