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())); } }
相关文章推荐
- 381. Insert Delete GetRandom O(1) - Duplicates allowed
- 381. Insert Delete GetRandom O(1) - Duplicates allowed
- 381. Insert Delete GetRandom O(1) - Duplicates allowed
- 381. Insert Delete GetRandom O(1) - Duplicates allowed
- 381. Insert Delete GetRandom O(1) - Duplicates allowed
- 381. Insert Delete GetRandom O(1) - Duplicates allowed
- LeetCode Insert Delete GetRandom O(1) - Duplicates allowed
- LeetCode 381---Insert Delete GetRandom O(1) - Duplicates allowed
- 【Leetcode】Insert Delete GetRandom O(1) - Duplicates allowed
- Insert Delete GetRandom O(1) - Duplicates allowed in JAVA
- Insert Delete GetRandom O(1) - Duplicates allowed
- [LeetCode] Insert Delete GetRandom O(1) - Duplicates allowed 常数时间内插入删除和获得随机数 - 允许重复
- LeetCode Insert Delete GetRandom O(1) - Duplicates allowed
- Insert Delete GetRandom O(1) - Duplicates allowed 解法
- [LeetCode] Insert Delete GetRandom O(1) - Duplicates allowed
- Insert Delete GetRandom O(1) - Duplicates allowed
- leetcode之Insert Delete GetRandom O(1) - Duplicates allowed
- Leetcode Insert Delete GetRandom O(1) Duplicates allowed and Not allowed
- LeetCode-Insert Delete GetRandom O(1) - Duplicates allowed
- Leetcode: Insert Delete GetRandom O(1) - Duplicates allowed