LeetCode 380. 【Java】380. Insert Delete GetRandom O(1)
原题链接
中等
作者:
tt2767
,
2020-02-27 20:50:32
,
所有人可见
,
阅读 812
/*
1.1 功能性需求: 支持插入, 删除, 返回随机值
1.2 非功能性需求: 3个操作都O(1)
2.1 插入删除O(1)-> HashMap
2.2 getRandom O(1) -> 维护数组域,
2.3 普通数组的查找是O(n), 删除是Π(n), 删除最后一个元素是O(1),
因为本数组无需维护相互的关系性, 所以HashMap维护下对于val在数组中的位置, 删除时swap到最后去删除
*/
class RandomizedSet {
Map<Integer, Integer> map ;
List<Integer> list;
Random random;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<>();
list = new ArrayList<>();
random = 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) {
Integer idx = map.get(val);
if (idx != null) 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) {
Integer idx = map.get(val);
if (idx == null) return false;
map.put(list.get(list.size()-1), idx);
Collections.swap(list, idx, list.size()-1);
list.remove(list.size()-1);
map.remove(val);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
return list.get(random.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();
*/