Design a data structure that supports all following operations in average O(1) time.
insert(val): Inserts an item val to the set if not already present. remove(val): Removes an item val from the set if present. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
List 儲存 val
Map 儲存 val, store index
Remove val in list in constant, so we swap the number with last number in list and then delete the number in last position, it's O(1) operation
classRandomizedSet {List<Integer> list;Map<Integer,Integer> map; /** Initialize your data structure here. */publicRandomizedSet() { list =newArrayList<>(); map =newHashMap<>(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */publicbooleaninsert(int val) {if(map.containsKey(val)) returnfalse;map.put(val,list.size());System.out.println(val);list.add(val);returntrue; } /** Removes a value from the set. Returns true if the set contained the specified element. */publicbooleanremove(int val) {if(!map.containsKey(val)) returnfalse;int idx =map.get(val);// swap the val and last val in listif(idx <list.size()-1){int lastNum =list.get(list.size()-1);list.set(idx, lastNum);map.put(lastNum, idx); }list.remove(list.size()-1);map.remove(val);returntrue; } /** Get a random element from the set. */publicintgetRandom() {Random ran =newRandom();returnlist.get(ran.nextInt(list.size())); }}
classRandomizedCollection {List<Integer> list;Map<Integer,Set<Integer>> map; /** Initialize your data structure here. */publicRandomizedCollection() { list =newArrayList<>(); map =newHashMap<>(); } /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
publicbooleaninsert(int val) {boolean contain =map.containsKey(val);if(!contain) map.put(val,newHashSet<>());map.get(val).add(list.size());list.add(val);return!contain; } /** Removes a value from the collection. Returns true if the collection contained the specified element. */publicbooleanremove(int val) {if(!map.containsKey(val)) returnfalse;int idx =map.get(val).iterator().next();map.get(val).remove(idx);if(map.get(val).size() ==0) map.remove(val); if(idx <list.size()-1){int lastNum =list.get(list.size()-1);list.set(idx, lastNum);map.get(lastNum).remove(list.size()-1);map.get(lastNum).add(idx); }list.remove(list.size()-1);returntrue; } /** Get a random element from the collection. */publicintgetRandom() {Random ran =newRandom();returnlist.get(ran.nextInt(list.size())); }}