/**
* Initialize your data structure here.
*/
var RandomizedSet = function() {
this.set = {};
this.arr = { length: 0 };
};
/**
* Inserts a value to the set. Returns true if the set did not already contain the specified element.
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.insert = function(val) {
console.log('insert');
console.log('set:', this.set);
console.log('arr:', this.arr);
if (val === undefined) {
console.log('cannot insert undefined');
return false;
}
if (this.set[val] === undefined) {
// val does not exist yet, adding val
console.log('adding', val);
const index = this.arr.length++;
this.arr[index] = val;
this.set[val] = index;
console.log('new set:', this.set);
console.log('new arr:', this.arr);
return true;
} else {
// val exists, skip
console.log('valule exists:', val, 'not added')
return false;
}
};
/**
* Removes a value from the set. Returns true if the set contained the specified element.
* @param {number} val
* @return {boolean}
*/
RandomizedSet.prototype.remove = function(val) {
console.log('removing', val);
console.log('set:', this.set);
console.log('arr:', this.arr);
if (val === undefined) {
console.log('cannot remove undefined');
return false;
}
if (this.set[val] !== undefined && this.set[val] !== null) {
// val exists, removing from set
let index = this.set[val];
let last = this.arr.length - 1;
if (index !== last) {
// replace current value with last value
this.arr[index] = this.arr[last];
this.set[this.arr[index]] = index;
}
delete this.arr[last];
delete this.set[val];
--this.arr.length;
/*
check if index = last value in arr
if so, do nothing
else, overwrite value at index with last value in array
*/
/*
console.log('this arr index =', this.arr[index])
delete...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.