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();
Subscribe to see which companies asked this question
分析,与前一道题目类似,不一样的地方在于,集合中可以存在重复的元素,但是在插入的时候如果已存在需要插入的val时,则返回false,但是还是要把val插入到集合中。
ArrayList<Integer> list;
/** Initialize your data structure here. */
public RandomizedCollection() {
list = new ArrayList<Integer>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
boolean flag = !list.contains(val);
list.add(val);
return flag;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(!list.contains(val)){
return false;
}else{
list.remove((Integer)val);
return true;
}
}
/** Get a random element from the set. */
public int getRandom() {
if (list.size() == 1) {// 如果全排列的个数小于等于1个,则只需要返回base数组即可。
return list.get(0);
}
/* 随机生成一个下标 */
Random random = new Random();
int i = random.nextInt(list.size());
return list.get(i);
}