0380.cpp (582B)
1 class RandomizedSet { 2 public: 3 RandomizedSet() {} 4 5 bool insert(int val) { 6 if (um.count(val)) return false; 7 nums.emplace_back(val); 8 um[val] = nums.size() - 1; 9 return true; 10 } 11 12 bool remove(int val) { 13 if (!um.count(val)) return false; 14 int last = nums.back(); 15 um[last] = um[val]; 16 nums[um[val]] = last; 17 nums.pop_back(); 18 um.erase(val); 19 return true; 20 } 21 22 int getRandom() { return nums[rand() % nums.size()]; } 23 24 private: 25 vector<int> nums; 26 unordered_map<int, int> um; 27 };