class RandomizedSet {
Map<Integer, Integer> m;
List<Integer> l;
Random rand = new Random();
/** Initialize your data structure here. */
public RandomizedSet() {
m = new HashMap<Integer, Integer>();
l = new ArrayList<Integer>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if (m.containsKey(val)) return false;
m.put(val, l.size());
l.add(l.size(), val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if (! m.containsKey(val)) return false;
int loc = m.get(val);
int last = l.get(l.size() - 1);
l.set(loc, last);
m.put(last, loc);
l.remove(l.size()-1);
m.remove(val);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
return l.get(rand.nextInt(l.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();
*/
Runtime: 7 ms, faster than 99.93% of Java online submissions for Insert Delete GetRandom O(1).
Memory Usage: 43.8 MB, less than 73.72% of Java online submissions for Insert Delete GetRandom O(1).
이거...자신감이 넘처오르네요 ㅎ