• 381. Insert Delete GetRandom O(1)


    package LeetCode_381
    
    /**
     * 381. Insert Delete GetRandom O(1) - Duplicates allowed
     * https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/
     *
     * Design a data structure that supports all following operations in average O(1) time.
    Note: Duplicate elements are allowed.
    insert(val): Inserts an item val to the collection.
    remove(val): Removes an item val from the collection if present.
    getRandom: Returns a random element from current collection of elements.
    The probability of each element being returned is linearly related to the number of same value the collection contains.
     * */
    class RandomizedCollection() {
        /*
        *solution: HashMap+Array;
        * key of HashMap: number, value of HashMap is the list of index of the element in array,
        * Array<Pair<Int,Int>>, first: element, second: the index of element in the value(index list) of HashMap,
        * insert O(1): HashMap,
        * delete O(1), HashMap,
        * getRandom O(1), Array, because it save item in memory continuously
        * */
    
        /** Initialize your data structure here. */
        val map = HashMap<Int, ArrayList<Int>>()
        val list = ArrayList<Pair<Int, Int>>()
        val random = java.util.Random()
    
        /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
        fun insert(`val`: Int): Boolean {
            val indexList = map.getOrDefault(`val`, ArrayList())
            //add the index of element in array
            indexList.add(list.size)
            map.put(`val`, indexList)
            list.add(Pair(`val`, indexList.lastIndex))
            return indexList.size == 1
        }
    
        /** Removes a value from the collection. Returns true if the collection contained the specified element. */
        fun remove(`val`: Int): Boolean {
            if (!map.containsKey(`val`)) {
                return false
            }
            val indexList = map.get(`val`)
            val indexNeedEvict = indexList!!.get(indexList.lastIndex)
            val lastPair = list.get(list.lastIndex)
    
            //update index, replace the position between the element need to delete and the last element
            map.get(lastPair.first)!!.set(lastPair.second, indexNeedEvict)
            //swap
            list.set(indexNeedEvict, lastPair)
    
            //clean it
            list.removeAt(list.lastIndex)
            indexList.removeAt(indexList.lastIndex)
            if (indexList.size == 0) {
                map.remove(`val`)
            }
            return true
        }
    
        /** Get a random element from the collection. */
        fun getRandom(): Int {
            val randomIndex = random.nextInt(list.size)
            return list.get(randomIndex).first
        }
    }
    
    /**
     * Your RandomizedCollection object will be instantiated and called as such:
     * var obj = RandomizedCollection()
     * var param_1 = obj.insert(`val`)
     * var param_2 = obj.remove(`val`)
     * var param_3 = obj.getRandom()
     */

    related:

    380. Insert Delete GetRandom O(1)

  • 相关阅读:
    编写一个函数print,打印一个学生的成绩数组,该数组中有5个学生的数据记录,每个记录包括num,name,score[3],用主函数输人这些记录,用print函数输出这些记录
    Windows 隐藏 远程桌面(连接栏)
    chm文档生成->Sandcastle使用帮助
    流文件保存到本地的两种方法
    关于winform 调用本地html页面路径不正确问题
    winform time.AddMinutes 时间相加
    winform 登录后跳转百度地图报错 使用委托解决
    sql 更新列表中最老的一条数据
    WINFORM 输出txt文件
    dictionary 应用(绑定dgv)
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13621295.html
Copyright © 2020-2023  润新知