2018-10-19 Insert Delete GetRandom O(1) [M]

  1. Insert Delete GetRandom O(1)
    Design a data structure that supports all following operations in average O(1) time.
    LC 380
  • insert(val): Inserts an item val to the set if not already present.
  • remove(val): Removes an item val from the set if present.
  • getRandom: Returns a random element from current set of elements.

Each element must have the same probability of being returned.

import random
class RandomizedSet:
    
    def __init__(self):
        self.num = []
        self.pos = {}
        
    """
    @param: val: a value to the set
    @return: true if the set did not already contain the specified element or false
    """
    def insert(self, val):
        if val in self.pos:
            return False
        self.pos[val] = len(self.num)
        self.num.append(val)
        return True
    """
    @param: val: a value from the set
    @return: true if the set contained the specified element or false
    """
    def remove(self, val):
        if val in self.pos:
            idx, last = self.pos[val], self.num[-1]
            # val is replaced by the last element of self.num
            # while all others unchanged
            self.pos[last] = idx
            self.num.pop
            del self.pos[val] # or self.pos.pop(val, 0)
            return True
        return False
        
    """
    @return: Get a random element from the set
    """
    def getRandom(self):
        return self.num[random.randint(0, len(self.num) - 1)]

# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param = obj.insert(val)
# param = obj.remove(val)
# param = obj.getRandom()
  • Time O(1)
  • Space O(n)

Note:

  1. One key is to have:
    one num list (for choosing random number)
    one pos set (for O(1) look up time).

  2. Another key point for me is in remove(val). That is I can switch the last one with the removed one. As a result, other numbers' positions are unchanged.

  3. remember usage of random (inclusive)

import random
random_num = random.randint(0, len(list) - 1)

Example
// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();

// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);

// Returns false as 2 does not exist in the set.
randomSet.remove(2);

// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);

// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();

// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);

// 2 was already in the set, so return false.
randomSet.insert(2);

// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,920評論 0 13
  • Lua 5.1 參考手冊 by Roberto Ierusalimschy, Luiz Henrique de F...
    蘇黎九歌閱讀 14,257評論 0 38
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,862評論 0 10
  • 魯提轄拳打鎮(zhèn)關(guān)西 范家生 魯鎮(zhèn)的新貌讓歷史都感到驚奇與汗顏。這些年的變化的確太快了,以至于讓人有種目不暇接的感覺。...
    合肥拾貳樓閱讀 616評論 4 1
  • 1:從本篇文章中我學(xué)到的重要概念: 在聽力練習(xí)的過程中,一定注意聽關(guān)鍵的詞,并且認(rèn)真仔細(xì)聽文段中的話。 2:我在文...
    243李楠閱讀 191評論 2 1

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