Open xszi opened 3 years ago
Map + 数组
const RandomizeSet = function() {
this.map = new Map()
this.values = []
}
RandomizeSet.prototype.insert = function(val) {
// 存在
if(this.map.has(val)) {
return false
}
// 不存在
this.map.set(val, this.values.length)
this.values.push(val)
return true
}
RandomizeSet.prototype.remove = function(val) {
if(!this.map.has(val)) {
return false
}
const index = this.map.get(val)
// 存在且为最后一个元素
if(index === this.values.length - 1) {
this.values.pop()
this.map.delete(val)
} else {
// 存在不为最后一个元素,把最后一个位置的值填到删除的地方
const lastValue = this.values.pop()
this.values[index] = lastValue
this.map.set(lastValue, index)
this.map.delete(val)
}
return true
}
RandomizeSet.prototype.getRandom = function() {
const length = this.values.length
const random = Math.floor(Math.random() * length)
return this.values[random]
}
使用Set
const RandomizeSet = function() {
this.set = new Set()
}
RandomizeSet.prototype.insert = function(val) {
if (this.set.has(val)) {
return false
}
this.set.add(val)
return true
}
RandomizeSet.prototype.remove = function(val) {
if (!this.set.has(val)) {
return false
}
this.set.delete(val)
return true
}
RandomizeSet.prototype.getRandom = function() {
const random = parseInt(Math.random() * (this.set.size))
return [...this.set][random]
}
设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。
insert(val)
:当元素 val 不存在时,向集合中插入该项。remove(val)
:元素 val 存在时,从集合中移除该项。getRandom
:随机返回现有集合中的一项。每个元素应该有 相同的概率 被返回。示例 :