😲380 insert delete getrandom O(1)

https://leetcode.com/problems/insert-delete-getrandom-o1/description/

class RandomizedSet {
    private Map<Integer, Integer> map;
    private List<Integer> list;
    public RandomizedSet() {
        map = new HashMap<>();
        list = new ArrayList<>();
    }
    
    public boolean insert(int val) {
        if (map.containsKey(val)) {
            return false;
        }
        list.add(val);
        map.put(val, list.size() - 1);
        return true;
    }
    
    public boolean remove(int val) {
        if (!map.containsKey(val)) {
            return false;
        }
        int index = map.get(val);
        if (index == list.size() - 1) {
            map.remove(val);
            list.remove(index);
            return true;
        }
        map.remove(val);
        int tmp = list.get(list.size() - 1);
        list.remove(list.size() - 1);
        list.set(index, tmp);
        map.put(tmp, index);
        return true;
    }
    
    public int getRandom() {
        Random random = new Random();
        int index = random.nextInt(list.size());
        return list.get(index);
    }
}

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

注意如果你不care list里的顺序你是可以做到O(1) delete的,只需要把最后一个元素换到index的位置然后把最后一个元素删除掉,但是要注意如果index就是最后一个元素就直接删除,同时记得map里更新原本最后一个元素对应的index

注意random class的使用,nextInt的bound是non inclusive的

Last updated