题目就是让实现一个set结构,采用map+vector组合的方式可以实现。map建立数字和index之间的对应关系,vector存储set内容的值。
class RandomizedSet {PRivate: map<int,int> func; 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. */ bool insert(int val) { if(func.count(val)!=0) return false; nums.push_back(val); func[val]=nums.size()-1; return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ bool remove(int val) { if(func.count(val)==0) return false; int index=func[val]; func[nums[nums.size()-1]]=index; func.erase(val); int temp=nums[nums.size()-1]; nums[nums.size()-1]=nums[index]; nums[index]=temp; nums.pop_back(); return true; } /** Get a random element from the set. */ int getRandom() { 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(); */新闻热点
疑难解答