Custom DS Design
经典题目
380 Insert Delete GetRandom O(1)
Follow up, what if duplicates are allowed. LC 381
// HashMap + ArrayList
// 有个 corner case 需要 handle,就是调用 remove 操作时,
// list 中 只有一个元素 和 有多个元素 的情况,需要区分开来。
class RandomizedSet {
Map<Integer, Integer> map;
List<Integer> list;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<Integer, Integer>();
list = 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 (!map.containsKey(val)) {
map.put(val, list.size());
list.add(val);
return true;
}
return false;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if (map.containsKey(val)) {
int index = map.get(val);
// put the last element in the list to index
if (index == list.size() - 1) {
list.remove(list.size() - 1);
map.remove(val);
} else {
int tailValue = list.get(list.size() - 1);
list.set(index, tailValue);
// remove the last element
list.remove(list.size() - 1);
map.remove(val);
map.put(tailValue, index);
}
return true;
}
return false;
}
/** Get a random element from the set. */
public int getRandom() {
Random random = new Random();
return list.get(random.nextInt(list.size()));
}
}Last updated