Problem 380: Insert Delete GetRandom O(1)
思路
public class RandomizedSet {
ArrayList<Integer> list;
HashMap<Integer, Integer> map;
Random rand;
/** Initialize your data structure here. */
public RandomizedSet() {
list = new ArrayList<Integer>();
map = new HashMap<Integer, Integer>();
rand = new Random();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
boolean isContain = map.containsKey(val);
if (isContain) return false;
list.add(val);
map.put(val, list.size() - 1);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
boolean isContain = map.containsKey(val);
if (!isContain) return false;
int curPos = map.get(val);
if (curPos < list.size() - 1) {
int lastVal = list.get(list.size() - 1);
list.set(curPos, lastVal);
map.put(lastVal, curPos);
}
list.remove(list.size() - 1);
map.remove(val);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
return list.get(rand.nextInt(list.size()));
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/PreviousProblem 346: Moving Average from Data StreamNextProblem 381: Insert Delete GetRandom O(1) - Duplicates allowed
Last updated