资讯专栏INFORMATION COLUMN

leetcode380. Insert Delete GetRandom O(1)

phoenixsky / 1126人阅读

摘要:题目要求设计一个数据结构,使得能够在的时间复杂度中插入数字,删除数字,以及随机获取一个数字。因此,使用来查询时不可避免的。如何实现的随机查询这个其实就是强调一点,我们需要维持原有的插入顺序,从而保证各个元素等概率被随机。

题目要求
Design a data structure that supports all following operations in average O(1) time.

insert(val): Inserts an item val to the set if not already present.
remove(val): Removes an item val from the set if present.
getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
Example:

// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();

// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);

// Returns false as 2 does not exist in the set.
randomSet.remove(2);

// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);

// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();

// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);

// 2 was already in the set, so return false.
randomSet.insert(2);

// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();

设计一个数据结构,使得能够在O(1)的时间复杂度中插入数字,删除数字,以及随机获取一个数字。要求所有的数字都能够被等概率的随机出来。

思路和代码

其实有几个思路入手:

如何实现O(1)的插入

这里数字的插入还需要能够去重,即需要首先判断该数字是否已经存在,已经存在的话就不执行任何插入操作。如果底层是一个一般的数组,我们知道查询的时间复杂度为O(n),明显不满足题目的意思。一个有序的数组能够将查询的时间复杂度下降到O(lgn),但是这依然不满足条件1,而且也无法做到所有的元素被等概率的查询出来,因为每插入一个元素都将改动之前元素的位置。而唯一能够做到O(1)时间查询的只有一个数据结构,即hash。因此,使用hash来查询时不可避免的。

如何实现O(1)的删除

这个其实是一个很经典的问题了,只要能够利用hash在O(1)的时间内找到这个数字的位置,就有两种方法来实现O(1)的删除,一个是利用伪删除,即每一个位置都对应一个状态为,将状态位社会为已经删除即可,还有一种就更有意思,就是将被删除位替换为数组最后一位的值,然后只需要删除最后一位就行。这种删除就无需将删除位右侧的元素全部左移造成O(n)的时间复杂度。这里我们采用的是第二种方法。

如何实现O(1)的随机查询

这个其实就是强调一点,我们需要维持原有的插入顺序,从而保证各个元素等概率被随机。

综上所述,我们底层需要两种数据结构,一个hashmap来支持O(1)的查询,以及一个list来支持随机数的获取。代码实现如下:

public class InsertDeleteGetRandom_380 {
    private List list;
    private Map hash;
    
    public InsertDeleteGetRandom_380() {
        list = new ArrayList();
        hash = new HashMap();
    }
    
     /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
        if(hash.containsKey(val)) {
            return false;
        }
        list.add(val);
        hash.put(val, list.size()-1);
        return true;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
        if(!hash.containsKey(val)){
            return false;
        }
        int position = hash.get(val);
        if(position != list.size()-1) {
            int last = list.get(list.size()-1);
            list.set(position, last);
            hash.put(last, position);
        }
        list.remove(list.size()-1);
        hash.remove(val);

        return true;
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
        int position = (int)Math.floor((Math.random() * list.size()));
        return list.get(position);
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/73273.html

相关文章

  • Insert Delete GetRandom O(1) & Duplicates allo

    摘要:思路可以实现时间复杂度的和,但是要求也是,只用是不可以的。但是在里面查找的时间复杂度依然是,可以想到用来记录对应的,这样查找的时间也是常数。用可以保持顺序,但是的时间复杂度是。 380. Insert Delete GetRandom O(1) Design a data structure that supports all following operations in aver...

    2shou 评论0 收藏0
  • leetcode381. Insert Delete GetRandom O(1) - Duplic

    摘要:题目要求设计一个数据结构,支持能够在的时间内完成对数字的插入,删除和获取随机数的操作,允许插入重复的数字,同时要求每个数字被随机获取的概率和该数字当前在数据结构中的个数成正比。网上有一些实现采用来解决,这是不合理的。此时的代码如下 题目要求 Design a data structure that supports all following operations in average...

    h9911 评论0 收藏0
  • Design Phone Directory

    摘要:题目链接直接用一个,结果了看了加了个,不过感觉没什么必要加,反正保存的都一样,只是的时间大于,用可以保证。看了题目条件是可以随便返回一个值,但是不让这么做。很无语啊如果这道题要求要求的是的,那就和一样了。 Design Phone Directory 题目链接:https://leetcode.com/problems... 直接用一个set,结果tle了= = public clas...

    NicolasHe 评论0 收藏0
  • 哈希函数与哈希表

    摘要:哈希函数与哈希表一哈希函数哈希函数性质输入域是无穷的输出域有穷的当输入参数固定的情况下,返回值一定一样当输入不一样,可能得到一样的值。 哈希函数与哈希表 一、哈希函数 1.1 哈希函数性质: input输入域是无穷的 output输出域有穷的 当输入参数固定的情况下,返回值一定一样 当输入不一样,可能得到一样的值。(必然会出现,因为输入域很大,输出域很小),产生哈希碰撞 均匀分布的特...

    Rainie 评论0 收藏0
  • LeetCode[72] Edit Distance

    摘要:复杂度思路考虑用二维来表示变换的情况。如果两个字符串中的字符相等,那么如果两个字符串中的字符不相等,那么考虑不同的情况表示的是,从字符串到的位置转换到字符串到的位置,所需要的最少步数。 LeetCode[72] Edit Distance Given two words word1 and word2, find the minimum number of steps require...

    call_me_R 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<