算法学习记录(二十)

85 阅读1分钟

问:

  1. 380. O(1) 时间插入、删除和获取随机元素

解:

  1. 双哈希表,一个用来存位置,一个用来存值。添加节点时,一个表存key-index,另一个表存index-key。添加完size++。以便于生成随机数之后可以通过index去哈希表取值。删除时,应当把哈希表最后一个元素替换到删除的位置,再把元素删除,以避免出现空位。
class RandomizedSet {
    private mapSize: number
    private hashMap1: Map<number, number>
    private hashMap2: Map<number, number>
    constructor() {
        this.mapSize = 0
        this.hashMap1 = new Map()
        this.hashMap2 = new Map()
    }

    insert(key: number): boolean {
        if (this.hashMap2.has(key)) return false
        this.hashMap1.set(this.mapSize, key)
        this.hashMap2.set(key, this.mapSize)
        this.mapSize++
        return true
    }

    remove(key: number): boolean {
        if (!this.hashMap2.has(key)) return false
        const keyIdx = this.hashMap2.get(key)
        const lastKey = this.hashMap1.get(this.mapSize - 1)
        this.hashMap2.set(lastKey, keyIdx)
        this.hashMap2.delete(key)
        this.hashMap1.set(keyIdx, lastKey)
        this.hashMap1.delete(this.mapSize - 1)
        this.mapSize--
        return true
    }

    getRandom(): number {
        if (!this.mapSize) return
        const randNum = ~~(Math.random() * this.mapSize)
        return this.hashMap1.get(randNum)
    }
}