GetRandom O(1)
380. Insert Delete GetRandom O(1)
class RandomizedSet {
List<Integer> list;
Map<Integer, Integer> map;
/** Initialize your data structure here. */
public RandomizedSet() {
list = new ArrayList<>();
map = new HashMap<>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(map.containsKey(val)) return false;
map.put(val, list.size());
System.out.println(val);
list.add(val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(!map.containsKey(val)) return false;
int idx = map.get(val);
// swap the val and last val in list
if(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);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
Random ran = new Random();
return list.get(ran.nextInt(list.size()));
}
}381. Insert Delete GetRandom O(1) - Duplicates allowed
Last updated