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();
    }
};
相关推荐
渡我白衣几秒前
计算机组成原理(4):计算机的层次结构与工作原理
运维·c语言·网络·c++·人工智能·笔记·硬件架构
kkk_皮蛋7 分钟前
深入理解 WebRTC 临界锁实现与 C++ RAII 机制
开发语言·c++·webrtc
JANGHIGH15 分钟前
c++ 多线程(一)
开发语言·c++
神仙别闹17 分钟前
基于C++生成树思想的迷宫生成算法
开发语言·c++·算法
C语言小火车20 分钟前
红黑树(C/C++ 实现版)—— 用 “带配重的书架” 讲透本质
c语言·开发语言·c++·红黑树
梓䈑27 分钟前
【C++】C++11(右值引用和移动语义、可变参数模板 和 包装器)
java·开发语言·c++
好评12427 分钟前
【C++】一篇吃透容器适配器三件套:从stack/queue/priority_queue到deque底层
c++·stl·queue·stack
测试人社区—小叶子37 分钟前
Rust会取代C++吗?系统编程语言的新较量
运维·开发语言·网络·c++·人工智能·测试工具·rust
进击的荆棘1 小时前
C++起始之路——类和对象(中)
开发语言·c++
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——交易逆序对的总数
数据结构·算法·leetcode