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

相關文章
相關標籤/搜索