Insert Delete GetRandom O(1) - Duplicates allowed

来源:互联网 发布:php实战 商城系统开发 编辑:程序博客网 时间:2024/05/16 11:05

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

这个题和第一题的区别是可以加入重复的值,那么如果是简单的Map<Integer,Integer>显然会被覆盖掉,所以应该要用HashMap<Integer, Set<Integer>>()来解决。

然后得到Set中的第一个元素用到iterator:

public class RandomizedCollection {    Map<Integer, Set<Integer>> map;List<Integer> list;public RandomizedCollection() {map=new HashMap<Integer, Set<Integer>>();        list=new ArrayList<Integer>();    }        /** 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.get(val).add(list.size());    list.add(val);        return false;        }    else{    Set<Integer> set=new HashSet<>();    set.add(list.size());    map.put(val, set);    list.add(val);    return true;    }    }        /** 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;         }     Set<Integer> set=map.get(val);         Iterator<Integer> iterator=set.iterator();         int idx=iterator.next();         set.remove(idx);         if(set.isEmpty()){         map.remove(val);         }         int lastIdx=list.size()-1;         if (idx < lastIdx) {         int lastval=list.get(lastIdx);             list.set(idx, lastval);               map.get(lastval).remove(lastIdx);             map.get(lastval).add(idx);         }          list.remove(list.size()-1);         return true;    }        /** Get a random element from the collection. */    public int getRandom() {     int a = (int) (Math.random()*list.size());         return list.get(a);    }}



0 0
原创粉丝点击