380. 常数时间插入、删除和获取随机元素
1 class RandomizedSet 2 { 3 unordered_map<int,int> hash; 4 vector<int> nums; 5 public: 6 /** Initialize your data structure here. */ 7 RandomizedSet() 8 { 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 { 15 if(hash.count(val) > 0) return false; 16 else 17 { 18 nums.push_back(val); 19 hash.insert({val,nums.size() - 1}); 20 return true; 21 } 22 } 23 24 /** Removes a value from the set. Returns true if the set contained the specified element. */ 25 bool remove(int val) 26 { 27 if(hash.count(val) == 0) return false; 28 else 29 { 30 int index = hash[val]; 31 32 hash[nums.back()] = hash[val];//nums最后一个值的哈希值进行更新 33 34 swap(nums[index],nums[nums.size() - 1]);//对最后一个值进行删除 35 nums.pop_back(); 36 37 hash.erase(val); 38 39 return true; 40 } 41 } 42 43 /** Get a random element from the set. */ 44 int getRandom() 45 { 46 return nums[rand() % (int)nums.size()]; 47 } 48 }; 49 50 /** 51 * Your RandomizedSet object will be instantiated and called as such: 52 * RandomizedSet* obj = new RandomizedSet(); 53 * bool param_1 = obj->insert(val); 54 * bool param_2 = obj->remove(val); 55 * int param_3 = obj->getRandom(); 56 */
Mamba never out

浙公网安备 33010602011771号