LeetCode 380. Insert Delete GetRandom O(1)

Design a data structure that supports all following operations in average O(1) time.

  1. insert(val): Inserts an item val to the set if not already present.
  2. remove(val): Removes an item val from the set if present.
  3. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

Example:

// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();

// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);

// Returns false as 2 does not exist in the set.
randomSet.remove(2);

// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);

// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();

// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);

// 2 was already in the set, so return false.
randomSet.insert(2);

// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

解析:设计一个数据结构,实现插入、删除和随机访问的时间复杂度为O(1)。vector的插入和访问可以实现O(1)级别的,但是要判断vector中是否存在某个元素需要挨个进行比对,这样的复杂度是O(N)级别,但是Map可以弥补这个,所以考虑map+vector,map中存放元素和元素在vector中的下标位置,这样插入的时候先判断map中是否存在元素,如果不存在则插入到数据中,同时在map中记录对应关系。vector中删除的处理比较特别,中间的元素不好处理,所以可以将要删除的元素跟最后一个元素置换,然后直接删除最后一个元素。具体代码如下:

class RandomizedSet {
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(indexs.find(val) != indexs.end())
            return false;
        else
        {
            nums.push_back(val);
            indexs[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(indexs.find(val) == indexs.end())
            return false;
        int last = nums.back();
        indexs[last] = indexs[val];
        nums[indexs[val]] = last;
        nums.pop_back();
        indexs.erase(val);
        return true;
    }
    
    /** Get a random element from the set. */
    int getRandom() {
        return nums[rand() % nums.size()];
    }
    vector<int> nums;
    unordered_map<int, int> indexs;
};

/**
 * 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();
 */

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据