题目: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.
题目很简单,跟之前一道题目很像,使用HashMap和Set加上List的组合实现各个函数即可。直接上代码:
public class RandomizedCollection {
ArrayList<Integer> result;
HashMap<Integer, LinkedHashSet<Integer>> map;
public RandomizedCollection() {
result = new ArrayList<Integer>();
map = new HashMap<Integer, LinkedHashSet<Integer>>();
}
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
// Add item to map if it doesn't already exist.
boolean alreadyExists = map.containsKey(val);
if(!alreadyExists) {
map.put(val, new LinkedHashSet<Integer>());
}
map.get(val).add(result.size());
result.add(val);
return !alreadyExists;
}
/** 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;
}
// Get arbitary index of the ArrayList that contains val
LinkedHashSet<Integer> valSet = map.get(val);
int indexToReplace = valSet.iterator().next();
// Obtain the set of the number in the last place of the ArrayList
int numAtLastPlace = result.get(result.size() - 1);
LinkedHashSet<Integer> replaceWith = map.get(numAtLastPlace);
// Replace val at arbitary index with very last number
result.set(indexToReplace, numAtLastPlace);
// Remove appropriate index
valSet.remove(indexToReplace);
// Don't change set if we were replacing the removed item with the same number
if(indexToReplace != result.size() - 1) {
replaceWith.remove(result.size() - 1);
replaceWith.add(indexToReplace);
}
result.remove(result.size() - 1);
// Remove map entry if set is now empty, then return
if(valSet.isEmpty()) {
map.remove(val);
}
return true;
}
/** Get a random element from the collection. */
public int getRandom() {
// Get linearly random item
return result.get((int)(Math.random() * result.size()));
}
}