Insert Delete GetRandom O(1) - LeetCode

https://leetcode.com/problems/insert-delete-getrandom-o1/description/?envType=study-plan-v2&envId=top-interview-150

LeetCode_Sharing.png

Implement the RandomizedSet class:

  • RandomizedSet() Initializes the RandomizedSet object.
  • bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
  • bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
  • int getRandom() Returns a random element from the current set of elements (it’s guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.

You must implement the functions of the class such that each function works in average O(1) time complexity.

Example 1:

Input
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]

Explanation
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.

Constraints:

  • 231 <= val <= 231 - 1
  • At most 2 * 105 calls will be made to insert, remove, and getRandom.
  • There will be at least one element in the data structure when getRandom is called.

解析

按照要求,写出了下面的内容,但是时间用的有点多,题目要求是O(1)复杂度,对于我们的解法,value in 的写法是O(n),因此想别的方法来做。字典是O(1)的,因此用字典来查找,也就是通过value查index。

import random

class RandomizedSet:

    def __init__(self):
        self.content = []
    def insert(self, val: int) -> bool:
        if val not in self.content:
            self.content.append(val)
            return True
        else:
            return False
    def remove(self, val: int) -> bool:
        if val in self.content:
            self.content.remove(val)
            return True
        else:
            return False
    def getRandom(self) -> int:
        index = random.randint(1, len(self.content))
        return self.content[index - 1]

改进后的版本。

class RandomizedSet:
    def __init__(self):
        self.val_list = []
        self.index_dict = {}
    def insert(self, val: int) -> bool:
        if val not in self.index_dict:
            self.val_list.append(val)
            self.index_dict[val] = len(self.val_list) - 1
            return True
        return False
    def remove(self, val: int) -> bool:
        if val in self.index_dict:
            temp = self.val_list[-1]
            index = self.index_dict[val]
            self.val_list[index] = temp
            self.index_dict[temp] = index
            self.val_list.pop()
            del self.index_dict[val]
            return True
        return False
    def getRandom(self) -> int:
        return random.choice(self.val_list)
class RandomizedSet {
private:
    std::vector<int> val_list;
    std::unordered_map<int, int> index_map;

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

    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
        if (index_map.find(val) != index_map.end()) {
            int temp = val_list.back();
            int index = index_map[val];

            val_list[index] = temp;
            index_map[temp] = index;

            val_list.pop_back();
            index_map.erase(val);

            return true;
        }
        return false;
    }

    /** Get a random element from the set. */
    int getRandom() {
        int index = rand() % val_list.size();
        return val_list[index];
    }
};
class RandomizedSet {
    List<Integer> valList = new ArrayList<>();
    Map<Integer, Integer> indexMap = new HashMap<>();
    Random rand = new Random();
    public RandomizedSet() {

    }

    public boolean insert(int val) {
        if (!indexMap.containsKey(val)){
            valList.add(val);
            indexMap.put(val, valList.size() - 1);
            return true;
        }
        return false;
    }

    public boolean remove(int val) {
        if (indexMap.containsKey(val)){
            int temp = valList.get(valList.size() - 1);
            int index = indexMap.get(val);

            valList.set(index, temp);
            indexMap.put(temp, index);

            valList.remove(valList.size() - 1);
            indexMap.remove(val);

            return true;
        }
        return false;
    }

    public int getRandom() {
        return valList.get(rand.nextInt(valList.size()));
    }
}

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet obj = new RandomizedSet();
 * boolean param_1 = obj.insert(val);
 * boolean param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */