sisterAn / JavaScript-Algorithms

基础理论+JS框架应用+实践,从0到1构建整个前端算法体系
5.51k stars 634 forks source link

leetcode380:常数时间插入、删除和获取随机元素的解答 #51

Closed jasonting5 closed 4 years ago

jasonting5 commented 4 years ago
/**
 * Initialize your data structure here.
 */
var RandomizedSet = function() {
    this.arr = new Set()
};

/**
 * 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) {
    if (this.arr.has(val)) {
        return false
    }
    this.arr.add(val)
    return true
};

/**
 * 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) {
    if (!this.arr.has(val)) {
        return false
    }
    this.arr.delete(val)
    return true
};

/**
 * Get a random element from the set.
 * @return {number}
 */
RandomizedSet.prototype.getRandom = function() {
    const random = parseInt(Math.random()*(this.arr.size))
    return [...this.arr][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()
 */
sisterAn commented 4 years ago

牛掰了