二刷380. Insert Delete GetRandom O(1)

Medium
題目要求是Design a data structure that supports all following operations in average O(1) time.難點(diǎn)在于remove的時(shí)候如何做到average O(1). 這里用HashMap存val - index pair, 用ArrayList存val. remove()的方法是交換要remove的index和最后一個(gè)加入的元素的index,這樣可以做到O(1).

class RandomizedSet {
    Map<Integer, Integer> valIndexMap;
    List<Integer> valList;
    /** Initialize your data structure here. */
    public RandomizedSet() {
        valIndexMap = new HashMap<>();
        valList = new ArrayList<>();
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
        if (valIndexMap.containsKey(val)){
            return false;
        }
        valIndexMap.put(val, valList.size());
        valList.add(val);
        return true;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
        if (!valIndexMap.containsKey(val)){
            return false;    
        }
        valIndexMap.put(valList.get(valList.size() - 1), valIndexMap.get(val));
        valIndexMap.remove(val);
        valList.remove((Integer) val);
        return true;
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
        Random r = new Random();
        return valList.get(r.nextInt(valList.size()));
    }
}

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

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

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