LeetCode-432:全 O(1) 的数据结构

一、题目描述

在这里插入图片描述

class AllOne
{
private:
    class Node
    {
    public:
        string str;
        int num;
        Node(string s, int n)
        {
            str = s;
            num = n;
        }
        friend bool operator<(const Node &a, const Node &b)
        {
            if (a.num != b.num)
                return a.num < b.num;
            else
                return a.str < b.str;
        }
        friend bool operator>(const Node &a, const Node &b)
        {
            if (a.num != b.num)
                return a.num > b.num;
            else
                return a.str > b.str;
        }
        friend bool operator==(const Node &a, const Node &b)
        {
            return a.num == b.num && a.str == b.str;
        }
    };
    unordered_map<string, int> ump;
    set<Node> st;
    unordered_map<string, set<Node>::iterator> stump;

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)
    {
        if (ump.find(key) == ump.end())
            ump.insert(pair(key, 1));
        else
        {
            ump[key]++;
            st.erase(stump[key]);
            stump.erase(key);
        }
        auto iter = st.insert(Node(key, ump[key]));
        stump[key] = iter.first;
    }

    /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
    void dec(string key)
    {
        if (ump.find(key) != ump.end())
        {
            if (ump[key] == 1)
            {
                ump.erase(key);
                st.erase(stump[key]);
                stump.erase(key);
            }
            else
            {
                ump[key]--;
                st.erase(stump[key]);
                stump.erase(key);
                auto iter = st.insert(Node(key, ump[key]));
                stump[key] = iter.first;
            }
        }
    }

    /** Returns one of the keys with maximal value. */
    string getMaxKey()
    {
        if (ump.empty())
            return "";
        return (--st.end())->str;
    }

    /** Returns one of the keys with Minimal value. */
    string getMinKey()
    {
        if (ump.empty())
            return "";
        return st.begin()->str;
    }
};

四、运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44587168/article/details/106244231