classRandomizedSet{public:/** Inserts a value to the set. Returns true if the set did not already * contain the specified element. */boolinsert(intval){if(valToIndex.count(val))returnfalse;valToIndex[val]=vals.size();vals.push_back(val);returntrue;}/** Removes a value from the set. Returns true if the set contained the * specified element. */boolremove(intval){if(!valToIndex.count(val))returnfalse;constintindex=valToIndex[val];// Following two lines order are important when vals.size() == 1valToIndex[vals.back()]=index;valToIndex.erase(val);vals[index]=vals.back();vals.pop_back();returntrue;}/** Get a random element from the set. */intgetRandom(){constintindex=rand()%vals.size();returnvals[index];}private:unordered_map<int,int>valToIndex;// {val: index in vals}vector<int>vals;};
classRandomizedSet{/** * Inserts a value to the set. Returns true if the set did not already contain the specified * element. */publicbooleaninsert(intval){if(valToIndex.containsKey(val))returnfalse;valToIndex.put(val,vals.size());vals.add(val);returntrue;}/** Removes a value from the set. Returns true if the set contained the specified element. */publicbooleanremove(intval){if(!valToIndex.containsKey(val))returnfalse;finalintindex=valToIndex.get(val);// Following two lines order are important when vals.size() == 1valToIndex.put(last(vals),index);valToIndex.remove(val);vals.set(index,last(vals));vals.remove(vals.size()-1);returntrue;}/** Get a random element from the set. */publicintgetRandom(){finalintindex=rand.nextInt(vals.size());returnvals.get(index);}privateMap<Integer,Integer>valToIndex=newHashMap<>();// {val: index in vals}privateList<Integer>vals=newArrayList<>();privateRandomrand=newRandom();privateintlast(List<Integer>vals){returnvals.get(vals.size()-1);}}
classRandomizedSet:def__init__(self):""" Initialize your data structure here. """self.vals=[]self.valToIndex=defaultdict(int)definsert(self,val:int)->bool:""" Inserts a value to the set. Returns true if the set did not already contain the specified element. """ifvalinself.valToIndex:returnFalseself.valToIndex[val]=len(self.vals)self.vals.append(val)returnTruedefremove(self,val:int)->bool:""" Removes a value from the set. Returns true if the set contained the specified element. """ifvalnotinself.valToIndex:returnFalseindex=self.valToIndex[val]self.valToIndex[self.vals[-1]]=indexdelself.valToIndex[val]self.vals[index]=self.vals[-1]self.vals.pop()returnTruedefgetRandom(self)->int:""" Get a random element from the set. """index=randint(0,len(self.vals)-1)returnself.vals[index]