Quoestion: ClickHere
Solution:
Data Structure We are going to use is Array
1.insert(val):Before inserting check if number is already in array or not.If it is there then return False otherwise add element at end of array and return True
2.remove(val):check if number is already in array or not.If it is present then delete it and return True if it is not present Return False
3.getRandom:Return a Random number from list
Python Code:
import random
class RandomizedSet:
def __init__(self):
self.ds = []
self.indexes = {}
def insert(self, val: int) -> bool:
if val not in self.indexes:
self.ds.append(val)
self.indexes[val] = len(self.ds)-1
return True
return False
def remove(self, val: int) -> bool:
if val in self.indexes:
self.ds.remove(val)
del self.indexes[val]
return True
else:
return False
def getRandom(self) -> int:
return random.choice(self.ds).
0 Comments