Insert Delete GetRandom O(1) - Duplicates allowed

題目來源
和上一題有點(diǎn)類似,求插入刪除取隨機(jī)O(1)完成,區(qū)別在于可以重復(fù)。所以maps中需要vector來存儲,然后nums中需要存一下這個(gè)元素在maps中的vector中的哪個(gè)位置。題目不難,就是比較繞。

class RandomizedCollection {
public:
    /** Initialize your data structure here. */
    RandomizedCollection() {
        
    }
    
    /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
    bool insert(int val) {
        bool res = true;
        if (maps.count(val) != 0)
            res = false;
        nums.push_back(make_pair(val, maps[val].size()));
        maps[val].push_back(nums.size()-1);
        return res;
    }
    
    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    bool remove(int val) {
        if (maps.count(val) != 0) {
            maps[nums.back().first][nums.back().second] = maps[val].back();
            nums[maps[val].back()] = nums.back();
            nums.pop_back();
            maps[val].pop_back();
            if (maps[val].size() == 0)
                maps.erase(val);
            return true;
        }
        else
            return false;
    }
    
    /** Get a random element from the collection. */
    int getRandom() {
        return nums[rand() % nums.size()].first;
    }
private:
    unordered_map<int, vector<int>> maps;
    vector<pair<int, int>> nums;
};

/**
 * Your RandomizedCollection object will be instantiated and called as such:
 * RandomizedCollection obj = new RandomizedCollection();
 * bool param_1 = obj.insert(val);
 * bool param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容