Advertisement
pb_jiang

lc381

Oct 9th, 2022
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. struct Node {
  2.     int pos;
  3.     int val;
  4. };
  5. class RandomizedCollection {
  6.     using NP=Node*;
  7.     unordered_map<int, vector<Node*>> pos;
  8.     vector<Node*> elements;
  9.     int avail = 0;
  10. public:
  11.     RandomizedCollection() {
  12.     }
  13.    
  14.     bool insert(int val) {
  15.         bool ret = (pos.count(val) ? pos[val].size() == 0 : true);
  16.         int id = pos[val].size();
  17.         Node* n = new Node{id, val};
  18.         elements.push_back(n);
  19.         pos[val].push_back(n);
  20.         return ret;
  21.     }
  22.    
  23.     bool remove(int val) {
  24.         bool ret = (pos.count(val) ? pos[val].size() != 0 : false);
  25.         if (ret) {
  26.             auto e_last = elements.back();
  27.             auto tobedelete = pos[val].back();
  28.             int v2 = e_last->val, p2 = e_last->pos;
  29.            
  30.             swap(*e_last, *tobedelete);
  31.             pos[v2][p2] = tobedelete;
  32.  
  33.             elements.pop_back();
  34.             pos[val].pop_back();
  35.         }
  36.         return ret;
  37.     }
  38.    
  39.     int getRandom() {
  40.         int n = elements.size();
  41.         return elements[rand() % n]->val;
  42.     }
  43. };
  44.  
  45. /**
  46.  * Your RandomizedCollection object will be instantiated and called as such:
  47.  * RandomizedCollection* obj = new RandomizedCollection();
  48.  * bool param_1 = obj->insert(val);
  49.  * bool param_2 = obj->remove(val);
  50.  * int param_3 = obj->getRandom();
  51.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement