美文网首页
657. Insert Delete GetRandom O(1

657. Insert Delete GetRandom O(1

作者: Mree111 | 来源:发表于2019-10-09 14:37 被阅读0次

Description

Design a data structure that supports all following operations in average O(1) time.

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.

Solution

较为简单, 使用哈希表存储val ->idx,注意remove时的update

import random
class RandomizedSet:
    def __init__(self):
        # do intialization if necessary
        self.val2idx = {}
        self.numbers =[]

    """
    @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):
        # write your code here
        self.numbers.append(val)
        self.val2idx[val]=len(self.numbers)

    """
    @param: val: a value from the set
    @return: true if the set contained the specified element or false
    """
    def remove(self, val):
        # write your code here
        if val in self.val2idx:
            idx = self.val2idx[val]
            del self.val2idx[val]
            del self.val2idx[self.numbers[-1]]
            self.val2idx[self.numbers[-1]]=idx
            self.numbers[idx]= self.numbers[-1]
            self.numbers=self.numbers[:-1]
            
            
            
        

    """
    @return: Get a random element from the set
    """
    def getRandom(self):
        if len(self.numbers)==0:
            return
        # write your code here
        return self.numbers[random.randint(0, len(self.numbers) - 1)]

      
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param = obj.insert(val)
# param = obj.remove(val)
# param = obj.getRandom()

相关文章

网友评论

      本文标题:657. Insert Delete GetRandom O(1

      本文链接:https://www.haomeiwen.com/subject/wbfgpctx.html