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();
    }
};
相关推荐
chh5638 分钟前
C++--string
java·开发语言·网络·c++·学习
J_yyy21 分钟前
基于Reactor的文件管理服务开发笔记
c++·笔记·reactor·多线程编程·muduo
李小小钦1 小时前
D. Storming Arasaka(Codeforces 2238)
c语言·开发语言·数据结构·c++·算法
卷无止境1 小时前
SFML 深度解读:一个教科书级 C++ 多媒体库的内功心法
c++·后端
小徐不徐说3 小时前
Qt 线程迁移机制完整实战指南(moveToThread)
开发语言·c++·qt·程序设计
盐焗鹌鹑蛋3 小时前
【C++】set和map
c++
j7~3 小时前
【算法】专题二:滑动窗口之水果成蓝,找到字符串中所有字⺟异位词等算法题
c++·算法·滑动窗口·水果成蓝·最小字串覆盖·优选算法精选
一拳一个呆瓜3 小时前
【STL】iostream 编程:文件输出流的成员函数
c++·stl
Huangjin007_3 小时前
【C++11篇(四)】新的类功能、lambda 与包装器详解
开发语言·c++
哥不想学算法12 小时前
【C++】字符串字面量拼接
开发语言·c++