You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classRandomizedSet{__val: Set<number>constructor(){this.__val=newSet()}insert(val: number): boolean{constisHas=this.__val.has(val)this.__val.add(val);return!isHas}remove(val: number): boolean{constisHas=this.__val.has(val)if(isHas){this.__val.delete(val);}returnisHas}getRandom(): number{constlen=this.__val.sizeconstindex=Math.floor(Math.random()*len)return[...this.__val][index]asnumber}}/** * Your RandomizedSet object will be instantiated and called as such: * var obj = new RandomizedSet() * var param_1 = obj.insert(val) * var param_2 = obj.remove(val) * var param_3 = obj.getRandom() */
varRandomizedSet=function(){this.stack=[];};/** * @param {number} val * @return {boolean} */RandomizedSet.prototype.insert=function(val){if(this.stack.includes(val))returnfalse;this.stack.push(val);returntrue;};/** * @param {number} val * @return {boolean} */RandomizedSet.prototype.remove=function(val){if(!this.stack.includes(val))returnfalse;constidx=this.stack.findIndex(item=>item===val)this.stack.splice(idx,1);returntrue;};/** * @return {number} */RandomizedSet.prototype.getRandom=function(){constrandom=Math.floor(Math.random()*this.stack.length);returnthis.stack[random];};/** * Your RandomizedSet object will be instantiated and called as such: * var obj = new RandomizedSet() * var param_1 = obj.insert(val) * var param_2 = obj.remove(val) * var param_3 = obj.getRandom() */
380. O(1) 时间插入、删除和获取随机元素
实现RandomizedSet 类:
RandomizedSet() 初始化 RandomizedSet 对象
bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false 。
bool remove(int val) 当元素 val 存在时,从集合中移除该项,并返回 true ;否则,返回 false 。
int getRandom() 随机返回现有集合中的一项(测试用例保证调用此方法时集合中至少存在一个元素)。每个元素应该有 相同的概率 被返回。
你必须实现类的所有函数,并满足每个函数的 平均 时间复杂度为 O(1) 。
示例:
解释
提示:
The text was updated successfully, but these errors were encountered: