Skip to content

Latest commit

 

History

History
46 lines (39 loc) · 1.43 KB

2022-11-29.md

File metadata and controls

46 lines (39 loc) · 1.43 KB

题目

  1. Insert Delete GetRandom O(1)

Implement the RandomizedSet class:

RandomizedSet() Initializes the RandomizedSet object. bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise. bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise. int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned. You must implement the functions of the class such that each function works in average O(1) time complexity.

思路

代码

var RandomizedSet = function() {
  this.values = []
  this.indexes = {}
};

RandomizedSet.prototype.insert = function(val) {
  if (val in this.indexes) {
    return false
  }
  this.indexes[val] = this.values.length
  this.values.push(val)
  return true
};

RandomizedSet.prototype.remove = function(val) {
  if (!(val in this.indexes)) {
    return false
  }
  const index = this.indexes[val]
  this.values[index] = this.values[this.values.length - 1]
  this.values.pop()
  this.indexes[this.values[index]] = index
  delete this.indexes[val]
  return true
};

RandomizedSet.prototype.getRandom = function() {
    const index = Math.floor(this.values.length * Math.random())
    return this.values[index]
};