C++ | Leetcode C++题解之第432题全O(1)的数据结构

题目:

题解:

cpp 复制代码
class AllOne {
    list<pair<unordered_set<string>, int>> lst;
    unordered_map<string, list<pair<unordered_set<string>, int>>::iterator> nodes;

public:
    AllOne() {}

    void inc(string key) {
        if (nodes.count(key)) {
            auto cur = nodes[key], nxt = next(cur);
            if (nxt == lst.end() || nxt->second > cur->second + 1) {
                unordered_set<string> s({key});
                nodes[key] = lst.emplace(nxt, s, cur->second + 1);
            } else {
                nxt->first.emplace(key);
                nodes[key] = nxt;
            }
            cur->first.erase(key);
            if (cur->first.empty()) {
                lst.erase(cur);
            }
        } else { // key 不在链表中
            if (lst.empty() || lst.begin()->second > 1) {
                unordered_set<string> s({key});
                lst.emplace_front(s, 1);
            } else {
                lst.begin()->first.emplace(key);
            }
            nodes[key] = lst.begin();
        }
    }

    void dec(string key) {
        auto cur = nodes[key];
        if (cur->second == 1) { // key 仅出现一次,将其移出 nodes
            nodes.erase(key);
        } else {
            auto pre = prev(cur);
            if (cur == lst.begin() || pre->second < cur->second - 1) {
                unordered_set<string> s({key});
                nodes[key] = lst.emplace(cur, s, cur->second - 1);
            } else {
                pre->first.emplace(key);
                nodes[key] = pre;
            }
        }
        cur->first.erase(key);
        if (cur->first.empty()) {
            lst.erase(cur);
        }
    }

    string getMaxKey() {
        return lst.empty() ? "" : *lst.rbegin()->first.begin();
    }

    string getMinKey() {
        return lst.empty() ? "" : *lst.begin()->first.begin();
    }
};
相关推荐
nju_spy29 分钟前
力扣每日一题(二)任务安排问题 + 区间变换问题 + 排列组合数学推式子
算法·leetcode·二分查找·贪心·排列组合·容斥原理·最大堆
代码对我眨眼睛34 分钟前
226. 翻转二叉树 LeetCode 热题 HOT 100
算法·leetcode·职场和发展
黑色的山岗在沉睡2 小时前
LeetCode 494. 目标和
算法·leetcode·职场和发展
Predestination王瀞潞4 小时前
IO操作(Num22)
开发语言·c++
宋恩淇要努力5 小时前
C++继承
开发语言·c++
江公望7 小时前
Qt qmlRegisterSingletonType()函数浅谈
c++·qt
逆小舟8 小时前
【C/C++】指针
c语言·c++·笔记·学习
江公望8 小时前
Qt QtConcurrent使用入门浅解
c++·qt·qml
我是华为OD~HR~栗栗呀9 小时前
23届考研-Java面经(华为OD)
java·c++·python·华为od·华为·面试
爱吃喵的鲤鱼9 小时前
仿mudou——Connection模块(连接管理)
linux·运维·服务器·开发语言·网络·c++