Advertisement
SalmaYasser

Untitled

Dec 18th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. class RandomizedSet {
  2. public:
  3. /** Initialize your data structure here. */
  4.  
  5. unordered_map <int , int> idx_val;
  6. unordered_map <int , int> val_idx;
  7. int w = 0;
  8. RandomizedSet() {
  9.  
  10. }
  11.  
  12. /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
  13. bool insert(int val) {
  14. if (val_idx.count(val) > 0)
  15. return false;
  16. idx_val[w] = val;
  17. val_idx[val] = w;
  18.  
  19. w++;
  20.  
  21. return true;
  22.  
  23. }
  24.  
  25. /** Removes a value from the set. Returns true if the set contained the specified element. */
  26. bool remove(int val) {
  27.  
  28. if (val_idx.count(val) == 0)
  29. return false;
  30.  
  31. w--;
  32.  
  33. int idx_del = val_idx[val];
  34. int val_w = idx_val[w];
  35.  
  36. idx_val[idx_del] = val_w;
  37. val_idx[val_w] = idx_del;
  38.  
  39. val_idx.erase(val);
  40. idx_val.erase(w);
  41.  
  42. return true;
  43.  
  44.  
  45. }
  46.  
  47. /** Get a random element from the set. */
  48. int getRandom() {
  49.  
  50.  
  51. return idx_val[rand() % w];
  52. }
  53. };
  54.  
  55. /**
  56. * Your RandomizedSet object will be instantiated and called as such:
  57. * RandomizedSet* obj = new RandomizedSet();
  58. * bool param_1 = obj->insert(val);
  59. * bool param_2 = obj->remove(val);
  60. * int param_3 = obj->getRandom();
  61. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement