/*
https://leetcode-cn.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/
设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构。
注意: 允许出现重复元素。
insert(val):向集合中插入元素 val。
remove(val):当 val 存在时,从集合中移除一个 val。
getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。
示例:
// 初始化一个空的集合。
RandomizedCollection collection = new RandomizedCollection();
// 向集合中插入 1 。返回 true 表示集合不包含 1 。
collection.insert(1);
// 向集合中插入另一个 1 。返回 false 表示集合包含 1 。集合现在包含 [1,1] 。
collection.insert(1);
// 向集合中插入 2 ,返回 true 。集合现在包含 [1,1,2] 。
collection.insert(2);
// getRandom 应当有 2/3 的概率返回 1 ,1/3 的概率返回 2 。
collection.getRandom();
// 从集合中删除 1 ,返回 true 。集合现在包含 [1,2] 。
collection.remove(1);
// getRandom 应有相同概率返回 1 和 2 。
collection.getRandom();
*/
const hash = {};//val=>index 相同val最后一个的下标
const array = [];//
function insert(val){
let prev = hash[val];//原来的val下标
let ele = {
val:val,prev:prev
};
hash[val] = array.length;
array.push(ele);
if(prev!=null){
array[prev].next = hash[val];
}
return prev==null;
}
function remove(val){
let index = hash[val];
if(index == null){
return false;
}
let last = array.length - 1;
let prev = hash[val] = array[index].prev;
if(prev!=null){
array[prev].next = array[index].next;
}
array[index] = array[last];
let prev2 = array[index].prev;
if(prev2!=null){
array[prev2].next = index;
}
let next2 = array[index].next;
if(next2!=null){
array[next2].prev = index;
}else{
hash[array[index].val] = index;
}
array.length--;
return true;
}
function random(){
let r = Math.random()*array.length;
return array[r|0].val;
}
function wrapPrint(fun){
return (...args)=>{
let res = fun(...args);
console.info(res);
console.info(`hash=>`);
console.info(hash);
console.info(`array=>`);
console.info(array);
return res;
};
}
insert = wrapPrint(insert);
remove = wrapPrint(remove);
/*
insert(1);
remove(1);
insert(1);
*/
//
insert(10);
insert(10);
insert(20);
insert(20);
insert(30);
insert(30);
remove(10);
remove(10);
remove(30);
remove(30);
方法二
const hash = {};//
const array = [];//
function insert(val){
let prev = hash[val];
let ele = {
val:val,prev:prev,index:array.length
};
hash[val] = ele;
array[array.length] = ele;
if(prev!=null){
prev.next = ele;
}
return prev==null;
}
function remove(val){
let ele = hash[val];
if(ele == null){
return false;
}
let last = array.length - 1;
let prev = hash[val] = ele.prev;
if(prev!=null){
prev.next = null;
}
array[ele.index] = array[last];
array[last].index = ele.index;
array.length--;
return true;
}
function random(){
let r = Math.random()*array.length;
return array[r|0].val;
}
function wrapPrint(fun){
return (...args)=>{
let res = fun(...args);
console.info(res);
console.info(`hash=>`);
console.info(hash);
console.info(`array=>`);
console.info(array);
return res;
};
}
insert = wrapPrint(insert);
remove = wrapPrint(remove);
/*
insert(1);
remove(1);
insert(1);*/
//
insert(10);
insert(10);
insert(20);
insert(20);
insert(30);
insert(30);
remove(10);
remove(10);
remove(30);
remove(30);