380. Insert Delete GetRandom O(1)

来源:互联网 发布:淘宝宝贝描述规则 编辑:程序博客网 时间:2024/05/16 17:59

题目就是让实现一个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(); */
0 0
原创粉丝点击