题目
解法:list+hashmap
list储存所有元素
hashmap中key为值,value为他储存在list中的index
insert是O(1)显而易见,关键是delete如何做到O(1)。
普通的删除元素操作比如erase是O(n)的。基本思想是替换和pop操作都是O(1)的
根据hashmap储存的值可以知道要删除的元素在哪个位置,把这个位置的元素用最后一个元素替换,然后把最后一个元素pop出来,同时更新hahsmap中最后一个元素储存的index
import random
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.dict = {
}
self.list = []
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 in self.dict:
return False
self.dict[val