classRandomizedSet { private: unordered_map<int,int> numToLocation; vector<int> nums; public: /** Initialize your data structure here. */ RandomizedSet() {
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ boolinsert(int val){ // 已存在,返回false if(numToLocation.count(val)){ returnfalse; } numToLocation[val] = nums.size(); nums.push_back(val); returntrue; }
/** Removes a value from the set. Returns true if the set contained the specified element. */ boolremove(int val){ // 删除一个不存在的元素,返回false if(!numToLocation.count(val)){ returnfalse; } // 相当于把最后一个元素放到要删除的位置,然后删除最后一个元素 int location = numToLocation[val]; // 记录要删除元素的位置 numToLocation[nums.back()] = location; // 把最后一个元素的位置标记为要删除元素的位置 numToLocation.erase(val); // 删除val nums[location] = nums.back(); nums.pop_back(); returntrue; }
/** Get a random element from the set. */ intgetRandom(){ return nums[rand() % nums.size()]; } };
/** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet* obj = new RandomizedSet(); * bool param_1 = obj->insert(val); * bool param_2 = obj->remove(val); * int param_3 = obj->getRandom(); */
// 删除表头 intdeleteHead(){ int val = head->next->key; head->next = head->next->next; head->next->prev = head; return val; } };
/** * Your LRUCache object will be instantiated and called as such: * LRUCache* obj = new LRUCache(capacity); * int param_1 = obj->get(key); * obj->put(key,value); */