/*
o(1)的时间用map能够实现;难度在于 如果想random的话 需要有个能有个数据结构能带有按递增顺序的连续的表示位置的指针,但数组,list这种结构都实现不了o(1)的搜索时间; 解决方法是与map配合使用;
1 建立map key是输入的单词, value是长度;(这样可以知道 这个单词是第几个存进去的);
2 建立list 按顺序add进list;需要注意的是这里面的单词和位置 需要对应上map里面的;
3 插入实现很简单 难度几乎都在remove,(1)找到map里面需要remove的单词的位置 并记录 这样可以除去map和list里面的数字
注意: 如果删除的是最后一位 那就直接删除就好 如果不是那就用下一步的操作
(2)把list里面需要删除的那一位置重新设置成最后一位的值 然后把最后一位删掉,map里面一
样把最后一位的值对应成已经删除的list里面位置的值;
4 利用random类生成一个自动的随机数;
*/
class RandomizedSet {
/** Initialize your data structure here. */
private Map<Integer, Integer> map;
private List<Integer> list;
public RandomizedSet() {
map = new HashMap<>();
list = new ArrayList<>();
}
/** 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)) {
return false;
} else {
map.put(val, list.size());
list.add(val);
return true;
}
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(!map.containsKey(val)) {
return false;
} else {
int pos = map.remove(val);
//注意 : 这里需要判断删除的是否是最后一位,两种情况要分别处理 不然会出状况;
if(pos != list.size() - 1) {
int last = list.get(list.size() - 1);
map.put(last, pos);
list.set(pos, last);
}
list.remove(list.size() - 1);
return true;
}
}
/** Get a random element from the set. */
public int getRandom() {
Random random = new Random();
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();
*/