LeetCode之Insert Delete GetRandom O(1)(Kotlin)

问题: git


方法: O(1)的时间复杂度经过Hash实现,选择HashSet做为容器;getRandom时候经过随机数获取Set下标,等几率输出结果。github

具体实现:bash

class InsertDeleteGetRandom {
    /** Initialize your data structure here. */
    private val set = mutableSetOf<Int>()

    private val rand = Random(System.currentTimeMillis())


    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    fun insert(`val`: Int): Boolean {
        return set.add(`val`)
    }

    /** Removes a value from the set. Returns true if the set contained the specified element. */
    fun remove(`val`: Int): Boolean {
        return set.remove(`val`)
    }

    /** Get a random element from the set. */
    fun getRandom(): Int {
        val index = rand.nextInt(0, set.size)
        return set.elementAt(index)
    }
}
复制代码

有问题随时沟通dom

具体代码实现能够参考Githubui

相关文章
相关标签/搜索