其实我的思路之前是对的,需要用dict和list,list的存在是为了方便随机选取元素。而dict的存在是为了方便删除和添加元素,
在此需要注意的一点是dict和set内部都是用hashmap实现的。
我之所以最后没能成功实现O(1)时间复杂度的算法要求,根源在于没能解决list删除元素的时间复杂度问题。我想了用dict的val保存key在list中的index。但是从dict中删除key是很快的,但是从list删除某个元素,则时间复杂度是O(n)。
而解决方法则是将list的最后一个元素拷贝到将要删除的元素的位置。然后最后只需要把最后一个元素pop掉就行了。其他的元素都不需要移动。(一点心得:在思考的时候,有时候你会遇到一个个困难点,这个时候不能因为这个困难点就畏难退缩,而是面对困难,积极分析想办法,突破困难,佛挡杀佛)
import random
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.data = {}
self.data_lst = []
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.data:
return False
else:
cur_ele_num = len(self.data_lst)
self.data[val] = cur_ele_num
self.data_lst.append(val)
return True
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val in self.data:
remove_ele_idx = self.data[val]
last_list_val = self.data_lst[-1]
self.data[last_list_val] = remove_ele_idx
self.data_lst[remove_ele_idx] = last_list_val
self.data.pop(val)
self.data_lst.pop()
return True
else:
return False
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return random.choice(self.data_lst)