跳转至

O(1) 时间插入、删除和获取随机元素⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class RandomizedSet {
private:
    unordered_map<int, int> dict;
    vector<int> listing;

public:
    RandomizedSet() {

    }

    bool insert(int val) {
        if (dict.count(val)) {
            return false;
        }

        dict[val] = listing.size();
        listing.emplace_back(val);
        return true;
    }

    bool remove(int val) {
        if (!dict.count(val)) {
            return false;
        }

        int index = dict[val];
        int lastElement = listing.back();
        listing[index] = lastElement;
        dict[lastElement] = index;

        listing.pop_back();
        dict.erase(val);

        return true;
    }

    int getRandom() {
        int randomIndex = rand() % listing.size();
        return listing[randomIndex];
    }
};

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet* obj = new RandomizedSet();
 * bool param_1 = obj->insert(val);
 * bool param_2 = obj->remove(val);
 * int param_3 = obj->getRandom();
 */