2018-10-19 Insert Delete GetRand

2018-10-20  本文已影响0人  WenshengL
  1. Insert Delete GetRandom O(1)
    Design a data structure that supports all following operations in average O(1) time.
    LC 380

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()

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();

上一篇下一篇

猜你喜欢

热点阅读