leetcode 381.Insert Delete GetRandom
阿新 • • 發佈:2018-09-12
方法 let vector size num back tor random contain
這道題中要求使用O(1)的方法來刪除和插入元素的,那麽首先需要尋找到對應的元素,這個可以使用map的O(1)的查詢時間的,然後是刪除對應的元素的,那麽可以根據 堆排序中類似的做法把最後面的元素插入到前面來並且置換掉對應的值的。
class RandomizedCollection { public: /** Initialize your data structure here. */ RandomizedCollection() { } /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element.*/ bool insert(int val) { m[val].insert(num.size()); num.push_back(val); return m[val].size()==1; } /** Removes a value from the collection. Returns true if the collection contained the specified element. */ bool remove(int val) { if(m[val].empty()) returnfalse; int pos=*m[val].begin(); m[val].erase(pos); if(pos!=num.size()-1){ int temp=num.back(); num[pos]=temp; m[temp].erase(num.size()-1); m[temp].insert(pos); } num.pop_back(); return true; }/** Get a random element from the collection. */ int getRandom() { return num[rand()%num.size()]; } private: vector<int> num; map<int, set<int>> m; }; /** * Your RandomizedCollection object will be instantiated and called as such: * RandomizedCollection obj = new RandomizedCollection(); * bool param_1 = obj.insert(val); * bool param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */
leetcode 381.Insert Delete GetRandom