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

414 阅读1分钟

问题:


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

具体实现:

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)
    }
}

有问题随时沟通

具体代码实现可以参考Github