Variable-length array + hash table solves the "O(1) time insertion, deletion and acquisition of random elements" problem

Eleven, O(1) time to insert, delete and get random elements

11.1. Requirements for the title

Implement the RandomizedSet class:
​ RandomizedSet() Initializes a RandomizedSet object.
​ bool insert(int val) When the element val does not exist, insert the item into the collection and return true; otherwise, return false.
​ bool remove(int val) When the element val exists, remove the item from the collection and return true; otherwise, return false.
​ int getRandom() Randomly returns an item in the existing collection (the test case guarantees that there is at least one element in the collection when this method is called). Each element should have the same probability of being returned.
You must implement all functions of the class and satisfy the average time complexity of each function is O(1).

示例:
输入
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
输出
[null, true, false, true, 2, true, false, 2]
解释
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomizedSet.remove(2); // 返回 false ,表示集合中不存在 2 。
randomizedSet.insert(2); // 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomizedSet.getRandom(); // getRandom 应随机返回 1 或 2 。
randomizedSet.remove(1); // 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomizedSet.insert(2); // 2 已在集合中,所以返回 false 。
randomizedSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。

提示:
-231 <= val <= 231 - 1
最多调用 insert、remove 和 getRandom 函数 2 * 105 次
在调用 getRandom 方法时,数据结构中 至少存在一个 元素。

Source: LeetCode
Link: https://leetcode-cn.com/problems/insert-delete-getrandom-o1

11.2. Problem solving ideas

  1. First define a List to store values ​​and map to store (val, index);

  2. Initialize the defined List and map in RandomizedSet;

  3. In insert, first determine whether there is a val in the map, if it exists, it is false, if it does not exist, add the val to the values ​​and update the map;

  4. In remove, first determine whether there is a val in the map, if it does not exist, it is false. If it exists, search for the index of the val in the map, then move the element to be deleted to the end, then remove the last element of values, and finally put The map can be updated and deleted;

  5. In getRandom, the random library function is first introduced, and finally the index of a number is randomly taken out and returned.

​ Use the containsKey() method of Map to detect whether the data (value) exists. If the key exists, it indicates that the data has been obtained once, then directly returns the value of the Key in the Map, whether it is nul or not; if the key If it does not exist, generate or obtain data, put it into the Map, and return the data.

11.3. Algorithms

class RandomizedSet {
    
    
    //array存放的是所有的values
    List<Integer> values;
    //map里面存放的是val和values存放的下标index之间的关系(val,index)
    Map<Integer,Integer> map; 

    //初始化
    public RandomizedSet() {
    
    
        values = new ArrayList();
        map = new HashMap();
    }
    
    //插入操作
    public boolean insert(int val) {
    
    
        //如果map中已经存在val,返回false
        if(map.containsKey(val)){
    
    
            return false;
        }
        //先将val添加到values
        values.add(val);
        //再更新map
        map.put(val,values.size()-1);
        return true;
    }
    
    //删除操作
    public boolean remove(int val) {
    
    
        //如果map中不包含val,返回false
        if(!map.containsKey(val)){
    
    
            return false;
        }
        //搜索val在map中的index
        int index = map.get(val);
        //将需要删除的元素移到末尾再删除,否则就会出现数据搬移
        int last = values.get(values.size()-1);
        values.set(index,last);
        //移除values最后一位元素
        values.remove(values.size()-1);
        //在map中更新
        map.put(last,index);
        //在map中删除
        map.remove(val);
        return true;
    }
    
    public int getRandom() {
    
    
        //先引入random的库函数
        Random random = new Random();
        //最后随机取出一个数的index并返回即可
        return values.get(random.nextInt(values.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();
 */

Reference video: B station up master Ronan0

Guess you like

Origin blog.csdn.net/qq_52916408/article/details/124144218