这题找对数据结构并没有很复杂。insert()需要O(1)并不能带来很多的提示,remove(int val)需要O(1)就比较明显了,如果你移除一个值而不是对应的位置需要O(1),那最容易做到的应该就是HashMap/HashSet了。然后你需要getRandom是O(1)的话就意味着你需要一个可以O(1)做到random access的数据结构,也就是数组array。所以目前看来你需要的就是一个array和hashmap的结合体。现在主要解决的问题就是remove在array上比较难以用O(1)解决,即使不是remove一个value而是remove一个index在array上直接操作也不是O(1),但有一个情况例外,就是移除array最后一个数字。介个时候,就可以有操作的空间。如果我们能够做到每次array上的remove都是remove最后一个,那么这个O(1)也就不难解决了。所以我们终极的解决方案就是,哈希表的key是数值,然后value是对应的位置。每次我们需要删除一个数字,我们先用hashmap找到它在array上的index,然后把它和目前array上最后一个数字进行交换,同时更新哈希表,最后再删除array上最后一个数字就好了。根据这个算法,得到代码如下:
class RandomizedSet {
HashMap<Integer, Integer> posMap;
ArrayList<Integer> data;
/** Initialize your data structure here. */
public RandomizedSet() {
this.data = new ArrayList<>();
this.posMap = 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 (posMap.containsKey(val)) return false;
this.data.add(val);
int pos = this.data.size() - 1;
posMap.put(val, pos);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if (!this.posMap.containsKey(val)) return false;
Integer prevPos = this.posMap.remove(val);
if (prevPos != this.data.size() - 1) {
this.data.set(prevPos, this.data.get(this.data.size() - 1));
this.posMap.put(this.data.get(this.data.size() - 1), prevPos);
}
this.data.remove(this.data.size() - 1);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
Random r = new Random();
int index = r.nextInt(this.data.size());
return this.data.get(index);
}
}