nikunjsoni

380

Jun 24th, 2021
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. class RandomizedSet {
  2. public:
  3.     /** Initialize your data structure here. */
  4.     RandomizedSet() {
  5.        
  6.     }
  7.    
  8.     /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
  9.     bool insert(int val) {
  10.         if (m.find(val) != m.end()) return false;
  11.         nums.emplace_back(val);
  12.         m[val] = nums.size() - 1;
  13.         return true;
  14.     }
  15.    
  16.     /** Removes a value from the set. Returns true if the set contained the specified element. */
  17.     bool remove(int val) {
  18.         if (m.find(val) == m.end()) return false;
  19.         int last = nums.back();
  20.         m[last] = m[val];
  21.         nums[m[val]] = last;
  22.         nums.pop_back();
  23.         m.erase(val);
  24.         return true;
  25.     }
  26.    
  27.     /** Get a random element from the set. */
  28.     int getRandom() {
  29.         return nums[rand() % nums.size()];
  30.     }
  31. private:
  32.     vector<int> nums;
  33.     unordered_map<int, int> m;
  34. };
Advertisement
Add Comment
Please, Sign In to add comment