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

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

Design a data structure that supports all following operations in average O(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();

My Solutions:

380不能有重复数字,而这道题可以有,不能像之前那道题那样建立每个数字和其坐标的映射了,但是可以建立数字和其所有出现位置的集合之间的映射, 所以原来的那个HashMap从<值-位置>,改成<值-位置的集合>。

插入的时候,是插入到位置的集合。查询也是找到list中的随机位置。

删除的时候,同样是将ArrayList的最后一个交换到前面,但是现在一个值有多个位置,所以我们要交换对位置,不能和原来一样直接替换。

class RandomizedCollection {

    Map<Integer, Set<Integer>> map;
    List<Integer> list;
    
    
    /** Initialize your data structure here. */
    public RandomizedCollection() {
        map = new HashMap<>();
        list = new ArrayList<>();
    }
    
    /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
    public boolean insert(int val) {
        if (!map.containsKey(val)) {
            map.put(val, new HashSet<>()); // map里value是val,对应的value是一个hashset
        }
        map.get(val).add(list.size()); // hashmap里val对应的hashset存入list此时的大小,也就是在数字在list里的index
        list.add(val);
        return map.get(val).size() == 1; // 如果val只有一个,hashset的size会是1;如果超过1个,size会大于1
    }
    
    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    public boolean remove(int val) {
        
        if (!map.containsKey(val)) return false;
        
        int index = map.get(val).iterator().next(); // want-to-delete element is the first element in the HashSet
        
        //swap last element with the want-to-delete element
        
        int last = list.get(list.size() - 1); // store the last element value in the list in a variable
        
        // set last element to be at index position in list
        list.set(index, last);     
        
        //remove want-to-delete element in the hashset
        map.get(val).remove(index);
            
        //reposition last element
        map.get(last).add(index); //put last element in index position
        map.get(last).remove(list.size() - 1);// remove last elem's original index
        
        // remove last element (the val we want to delete) in the list
        list.remove(list.size() - 1);
        //remove hashset if it is empty
        if (map.get(val).size() == 0) map.remove(val); 
        
        return true;
    }
    
    /** Get a random element from the collection. */
    public int getRandom() {
        Random r = new Random();
        int index = r.nextInt(list.size());
        return list.get(index);
    }
}

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

Last updated