public class RandomizedCollection {
private List<Integer> nums;
private Map<Integer,Set<Integer>> indexs;
private Random r;
/** Initialize your data structure here. */
public RandomizedCollection() {
nums=new ArrayList<Integer>();
indexs=new HashMap<Integer,Set<Integer>>();
r=new Random();
}
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
boolean contains=indexs.containsKey(val);
if(!contains)indexs.put(val, new LinkedHashSet<Integer>());
indexs.get(val).add(nums.size());
nums.add(val);
return !contains;
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
if(!indexs.containsKey(val))
return false;
int index=indexs.get(val).iterator().next();
indexs.get(val).remove(index);
if(index<nums.size()-1)
{
int lastone=nums.get(nums.size()-1);
nums.set(index, lastone);
indexs.get(lastone).remove(nums.size()-1);
indexs.get(lastone).add(index);
}
nums.remove(nums.size()-1);
if(indexs.get(val).isEmpty())
indexs.remove(val);
return true;
}
/** Get a random element from the collection. */
public int getRandom() {
return nums.get(r.nextInt(nums.size()));
}
}
381. Insert Delete GetRandom O(1) - Duplicates allowed
最新推荐文章于 2020-09-20 02:35:12 发布