美文网首页
8.21 - hard - 76

8.21 - hard - 76

作者: 健时总向乱中忙 | 来源:发表于2017-08-22 04:32 被阅读0次

381. Insert Delete GetRandom O(1) - Duplicates allowed

设计数据结构, 这种题目还是挺巧妙的

class RandomizedCollection(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.h = {}
        self.arr = []
        

    def insert(self, val):
        """
        Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
        :type val: int
        :rtype: bool
        """
        self.arr.append(val)
        if val in self.h:
            self.h[val].add(len(self.arr) - 1)
            return False
        else:
            self.h[val] = set([len(self.arr) - 1])
            return True

    def remove(self, val):
        """
        Removes a value from the collection. Returns true if the collection contained the specified element.
        :type val: int
        :rtype: bool
        """
        if val in self.h and self.h[val]:
            out, ins = self.h[val].pop(), self.arr[-1] # val的一个index,和最后一个值
            self.arr[out] = ins # 把那个index的值设置为arr的最后一个值
            if self.h[ins]: # 如果arr的最后一个值存在于h里
                self.h[ins].add(out)
                self.h[ins].discard(len(self.arr) - 1)
            self.arr.pop() #删掉arr的最后一个值
            return True
        return False 
        

    def getRandom(self):
        """
        Get a random element from the collection.
        :rtype: int
        """
        return random.choice(self.arr)

# Your RandomizedCollection object will be instantiated and called as such:
# obj = RandomizedCollection()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()

相关文章

  • 8.21 - hard - 76

    381. Insert Delete GetRandom O(1) - Duplicates allowed 设计...

  • 8.21 - hard - 74

    358. Rearrange String k Distance Apart 这道题就是把所有值都进行最大区分,在...

  • 8.21 - hard - 79

    407. Trapping Rain Water II 利用外围边界,依次朝里面找,只是新加入heap的值需要取其...

  • 8.21 - hard - 80

    410. Split Array Largest Sum 有两种解法: 按值二分: 左边界是array里的最大值,...

  • 8.21 - hard - 72

    352. Data Stream as Disjoint Intervals 有序的几个重要数据结构和算法:hea...

  • 8.21 - hard - 73

    354. Russian Doll Envelopes 简单的DP的话,会TLE,worst case O(n^2...

  • 8.21 - hard - 75

    363. Max Sum of Rectangle No Larger Than K 如果是求最大值,用for l...

  • 8.21 - hard - 77

    391. Perfect Rectangle 找出四个边角点。 所有的小矩形面积和等于大矩形面积 除了四个边角点,...

  • 8.21 - hard - 78

    403. Frog Jump首先做出来一个TLE的版本,因为这里面要search三种情况,可以用记忆化搜索来做。

  • 100个句型-4

    76、It took 时间+to It took years of hard work to speak good...

网友评论

      本文标题:8.21 - hard - 76

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