leetcode 380. Insert Delete GetRandom O(1)(在O(1)时间添加,删除,取随机)

这篇博客讨论了如何实现一个名为RandomizedSet的类,该类需要支持在常数时间内插入、删除元素以及随机获取集合中的一个元素。通过使用HashMap来存储元素及其索引,以及ArrayList来保存元素顺序,可以在O(1)时间内完成添加和删除操作。同时,通过记录插入时的索引并在删除时将待删除元素移到列表末尾,可以确保在O(1)时间内随机获取元素。此外,博客还提到了Java中的Random类用于生成随机索引。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Implement the RandomizedSet class:

RandomizedSet() Initializes the RandomizedSet object.
bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
int getRandom() Returns a random element from the current set of elements (it’s guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
You must implement the functions of the class such that each function works in average O(1) time complexity.

Example 1:

Input
[“RandomizedSet”, “insert”, “remove”, “insert”, “getRandom”, “remove”, “insert”, “getRandom”]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]

Explanation
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.

实现一个RandomizedSet类,它具有以下功能:
能在O(1)时间添加和删除元素,
并能在O(1)时间内,在现有的元素中随机(均匀分布)取一个。

添加元素时如果元素已经存在,返回false, 否则添加之后返回true.
删除元素也是一样,已经不存在的返回false, 否则删除完返回true.

思路:

在O(1)时间内添加和删除元素到是简单,一个hashset就搞定了。
问题在于如何在O(1)时间内随机返回现有数字中的一个,而且是均匀分布。

这里用Java, 不像cpp那样next函数可以直接指定偏移量从set中取值。

科普一下,random类中的nextInt(n)是从[0, n)中按均匀分布取值的。
把它当作下标的话,就只能从数组或list中取值了。
用数组不太现实,因为val的范围太广了,那么只能用list。

但是list有个问题,是它的删除不是O(1)的,因为要查找元素在哪,删除后还要移位。
那么问题就变成如何在O(1)时间从list中删除元素。
如果不需要查找,直接删除末尾的元素,类似pop,就是O(1),移位也省了.
那么就要把要删除的元素换到末尾去,
怎么在O(1)时间找到要删除的元素在哪呢,只需要在insert时记下它的下标。
所以需要一个hashmap.
换元素时,不要忘了更新hashmap中元素对应的下标。

class RandomizedSet {
    HashMap<Integer,Integer> map;
    List<Integer> arr;
    Random rd;

    public RandomizedSet() {
        map = new HashMap<>();
        arr = new ArrayList<>();
        rd = new Random();
    }
    
    public boolean insert(int val) {
        if(map.containsKey(val)) return false;
        map.put(val,arr.size());
        arr.add(val);
        return true;
    }
    
    public boolean remove(int val) {
        if(!map.containsKey(val)) return false;
        int valIdx = map.get(val);
        int lastItem = arr.get(arr.size()-1);
        //把val放到最后面去,最后面的元素值放到valIdx处,然后直接移掉list的最后一个元素
        arr.set(valIdx, lastItem);
        map.put(lastItem, valIdx); //map中要更新lastItem的index
        //arr.set(arr.size()-1, val); //反正都要remove了,还设置它干嘛
        arr.remove(arr.size()-1);
        
        map.remove(val);
        
        return true;
    }
    
    public int getRandom() {
        return arr.get(rd.nextInt(arr.size()));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值