380. Insert Delete GetRandom O(1)

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

  • insert(val): Inserts an item val to the set if not already present.
  • remove(val): Removes an item val from the set if present.
  • 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();
Show Company Tags
Hide Tags

S: hash_map + vector

删除时将要删除的数和vector末尾的数交换,再删除末尾,以达到O(1)的复杂度

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 (valToIdx.find(val) == valToIdx.end()) {
            valToIdx[val] = nums.size();
            nums.push_back(val);
            return true;
        } else {
            return false;
        }
    }

    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
        if (valToIdx.find(val) == valToIdx.end()) {
            return false;
        }
        int n = nums.size();
        int idx = valToIdx[val];
        valToIdx[nums[n - 1]] = idx;
        swap(nums[idx], nums[n - 1]);
        nums.pop_back();
        valToIdx.erase(val);
        return true;
    }

    /** Get a random element from the set. */
    int getRandom() {
        if (nums.size() == 0) {
            return 0;
        }
        int idx = rand() % nums.size();
        return nums[idx];
    }

private:
    unordered_map<int, int> valToIdx;
    vector<int> nums;
};

381. Insert Delete GetRandom O(1) - Duplicates allowed

Design a data structure that supports all following operations inaverageO(1)time.

Note: Duplicate elements are allowed.

  1. insert(val): Inserts an item val to the collection.
  2. remove(val): Removes an item val from the collection if present.
  3. getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.

Example:

// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection();

// Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1);

// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1);

// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2);

// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom();

// Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1);

// getRandom should return 1 and 2 both equally likely.
collection.getRandom();

S: 和上一题类似,只是hashmap存储的是 index list,每次随机删除一个index

//注意,没有通过最后一个test case
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) {
        bool result = numIndex.find(val) == numIndex.end();
        nums.push_back(val);
        numIndex[val].insert(nums.size() - 1);
        return result;
    }

    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    bool remove(int val) {
if (DDDDX        魄罗;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;浑南女女女女女女女女女女女女女女女女女女ex.find(val) == numIndex.end()) return false;
        int i = *numIndex[val].begin();
        int n = nums.size();
        if (i != n - 1) {
            numIndex[nums[n - 1]].erase(n - 1);
            numIndex[nums[n - 1]].insert(i);
            swap(nums[n - 1], nums[i]);
        }
        nums.pop_back();
        if (numIndex[val].size() == 1) {
            numIndex.erase(val);
        } else {
            numIndex[val].erase(i);
        }
        return true;
    }

    /** Get a random element from the collection. */
    int getRandom() {
        if (nums.size() == 0) return 0;
        return nums[rand() % nums.size()];
    }

private:
    vector<int> nums;
    unordered_map<int, unordered_set<int>> numIndex;
};

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

results matching ""

    No results matching ""