最右一面
40分钟,只手撕了一道zset实现估计kpi了,中年白发
using namespace std;
struct Compare{
bool operator()(const pair& p1, const pair& p2) {
if (p1.second == p2.second) {
return p1.first > p2.first; // 如果值相等,按键的字典序排序
}
return p1.second > p2.second; // 按值排序
}
};
class Zset
{
private:
set, Compare> s;
unordered_map sKey;
public:
//插入或更新key/val对,当key存在时更新对应的val,当key不存在时插入key/val对
void upsert(const std::string& key, int val){
auto it = sKey.find(key);
if(it != sKey.end()){
pair old = {key, it->second};
auto oldPair = s.find(old);
s.erase(oldPair);
s.insert({key, val});
sKey[key] = val;
}else{
s.insert({key, val});
sKey[key] = val;
}
}
//弹出val值最小的key/val对,有多个相同的最小val时任意弹出一个对应的key/val即可
bool pop(std::string& key, int& val){
if(s.empty()) return false;
auto it = s.begin();
s.erase(it);
sKey.erase(key);
return true;
}
// insert("a", 5)
// insert("b", 1)
// insert("c", 3)
// insert("a", 1)
// pop() -> 弹出("a", 1)或("b", 1)
};
using namespace std;
struct Compare{
bool operator()(const pair& p1, const pair& p2) {
if (p1.second == p2.second) {
return p1.first > p2.first; // 如果值相等,按键的字典序排序
}
return p1.second > p2.second; // 按值排序
}
};
class Zset
{
private:
set, Compare> s;
unordered_map sKey;
public:
//插入或更新key/val对,当key存在时更新对应的val,当key不存在时插入key/val对
void upsert(const std::string& key, int val){
auto it = sKey.find(key);
if(it != sKey.end()){
pair old = {key, it->second};
auto oldPair = s.find(old);
s.erase(oldPair);
s.insert({key, val});
sKey[key] = val;
}else{
s.insert({key, val});
sKey[key] = val;
}
}
//弹出val值最小的key/val对,有多个相同的最小val时任意弹出一个对应的key/val即可
bool pop(std::string& key, int& val){
if(s.empty()) return false;
auto it = s.begin();
s.erase(it);
sKey.erase(key);
return true;
}
// insert("a", 5)
// insert("b", 1)
// insert("c", 3)
// insert("a", 1)
// pop() -> 弹出("a", 1)或("b", 1)
};
全部评论
相关推荐

查看11道真题和解析