Advertisement
Guest User

Untitled

a guest
Aug 21st, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. from random import randrange
  2. class RandomizedSet(object):
  3.  
  4. def __init__(self):
  5. """
  6. Initialize your data structure here.
  7. """
  8. self.list, self.pos = [], {}
  9.  
  10.  
  11.  
  12. def insert(self, val):
  13. """
  14. Inserts a value to the set. Returns true if the set did not already contain the specified element.
  15. :type val: int
  16. :rtype: bool
  17. """
  18. if val in self.pos:
  19. return False
  20. else:
  21. self.list.append(val)
  22. self.pos[val] = len(self.list) - 1
  23. return True
  24.  
  25.  
  26. def remove(self, val):
  27. """
  28. Removes a value from the set. Returns true if the set contained the specified element.
  29. :type val: int
  30. :rtype: bool
  31. """
  32. # Replace it by self.list. Increases by 400 ms. Ideally both should have same number of elements.
  33. if val in self.pos:
  34. idx, last = self.pos[val], self.list[-1]
  35. self.list[idx], self.pos[last] = last, idx
  36. self.list.pop(); self.pos.pop(val, 0)
  37. return True
  38. return False
  39.  
  40.  
  41. def getRandom(self):
  42. """
  43. Get a random element from the set.
  44. :rtype: int
  45. """
  46. n = len(self.list)
  47. return self.list[random.randint(0,n-1)]
  48.  
  49.  
  50.  
  51.  
  52. # Your RandomizedSet object will be instantiated and called as such:
  53. # obj = RandomizedSet()
  54. # param_1 = obj.insert(val)
  55. # param_2 = obj.remove(val)
  56. # param_3 = obj.getRandom()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement