您的位置:首页 > 其它

Insert Delete GetRandom O(1) - Duplicates allowed

2016-09-07 17:10 375 查看
Design a data structure that supports all following operations in average
O(1) time.

Note: Duplicate elements are allowed.
insert(val)
: Inserts an item val to the collection.
remove(val)
: Removes an item val from the collection if present.
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();

这个题和第一题的区别是可以加入重复的值,那么如果是简单的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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: