您的位置:首页 > 其它

381. Insert Delete GetRandom O(1) - Duplicates allowed

2017-01-05 16:14 393 查看
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()));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: