哈希表是一种数据结构,它可以在平均情况下提供非常快速的插入、删除和查找操作。其基本思想是通过一个哈希函数将键(key)映射到一个特定的索引(index),然后将对应的值(value)存储在该索引位置。
CR 030. O(1) 时间插入、删除和获取随机元素: https://leetcode.cn/problems/FortPu/description/
import random
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.data = []
self.map = {}
def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
"""
if val not in self.map or (val in self.map and self.map[val] == None):
self.data.append(val)
self.map[val] = self.data.index(val)
return True
else:
return False
def remove(self, val: int) -> bool:
"""
Removes a value from the set. Returns true if the set contained the specified element.
"""
if val in self.map and self.map[val] is not None:
self.map[val] = None
return True
else:
return False
def getRandom(self) -> int:
"""
Get a random element from the set.
"""
while True:
randomIdx = random.randint(0, len(self.data) - 1)
if self.data[randomIdx] in self.map and self.map[self.data[randomIdx]] is not None:
return self.data[randomIdx]