Leetcode 381. Insert Delete GetRandom O(1) - Duplicates allowed 可重复常数增删改系统 解题报告

matlab电偶极子源码,电偶极子的MATLAB场模拟 电偶极子周围电场电势分布的MATLAB三维模拟Matlab可以用于模拟四维场的效果,本文以电偶极子的电场和电势场为例展示MATLAB在该方面领域的应用。摘要电偶极子由一个正电荷和一个负电荷组成,其电场和空间电势分布与单电荷相比具有一些重要的特性。本文将给出电场和电势场的近似表达式。这两个量的精确表达式是复杂的,不太常用,因此 MATLAB 被采用来操作精确值和绘制三维分布的远区域, 近区域和一侧区... 阅读详情

1 解题思想

这道题是380的进化版,其实也就是在插入的时候允许了重复的值,变的更加复杂了一些。
这道题是基于这题来的,所以请先看下这题,我只说下如何从380过渡到381
Leetcode 380. Insert Delete GetRandom O(1) 常数增删改系统 解题报告

因为一个值要多个位置,所以原来的那个HashMap肯定要从<值-位置>,改成<值-位置的集合>

那么查询还是直接操作ArrayList没有难度
而插入的时候,是插入到位置集合也没有难度

问题在于删除。

删除的时候,idea和之前380一样,同样是将ArrayList的最后一个交换到前面,但是现在一个值有多个位置,所以我们要交换对位置,不能和原来一样直接替换。

所以根据值的集合选的不同,有所不同:
如你可以使用:
ArrayList来存储集合,那么你替换的时候需要遍历一下位置替换
我选择了Stack,那么就需要保证出栈的顺序有保障

或者其他更高级的快速的结构,随你,只要方便就好。。思想就是380的拓展,懂了380这个自然能变

2 原题

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.

Example: 
// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection();

// Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1);

// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1);

// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2);

// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom();

// Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1);

// getRandom should return 1 and 2 both equally likely.
collection.getRandom();

3 AC解

public class RandomizedCollection {
    //用来索引下在ArrayList中的关系,做到快速定位
    private HashMap<Integer,Stack<Integer>> locations;
    //存储原始数据
    private ArrayList<Integer> list;
    private Random random;
    //为了排序,控制栈的
    ArrayList<Integer> tmpForStack;

    /** Initialize your data structure here. */
    public RandomizedCollection() {
        this.locations = new HashMap<Integer,Stack<Integer>>();
        this.list = new ArrayList<Integer>();
        this.random = new Random();
        this.tmpForStack = new ArrayList<Integer>();
    }


    /**
     * 直接插入
     * */
    public boolean insert(int val) {
        boolean flag = false;
        if( locations.containsKey(val) == false ){
            locations.put(val,new Stack<Integer>());
        }
        if(locations.get(val).isEmpty())
            flag = true;
        locations.get(val).push(list.size());
        list.add(val);
        return flag;
    }

    /** Removes a value from the set. Returns true if the set contained the specified element. */
    /**
     * 核心思想在于:把删除的元素交换到ArrayList最后一位上,这样就可以O1完成了,
     * 
     * 唯一的一点不同是,要保证在每一个元素对应的位置的栈,要保证其顺序是从小到大,每次出栈的一定是最大的,所以我这里交换List后,更新那个元素的栈时需要先把比他大的弹出来,再放回去
     * */
    public boolean remove(int val) {
        if( locations.containsKey(val) == false || locations.get(val).isEmpty() ) return false;
        int tmpLocation = locations.get(val).pop();
        if(tmpLocation != list.size() - 1){
            int lastVal = list.get(list.size() -1 );
            list.set(tmpLocation,lastVal);
            locations.get(lastVal).pop();
            tmpForStack.clear();
            while(locations.get(lastVal).isEmpty() == false && locations.get(lastVal).peek() > tmpLocation){
                tmpForStack.add(locations.get(lastVal).pop());
            }
            locations.get(lastVal).push(tmpLocation);
            for(int tval:tmpForStack)
                locations.get(lastVal).push(tval);
        }
        list.remove(list.size() - 1);
        return true;
    }

    /** Get a random element from the set. */
    public int getRandom() {
        return list.get(random.nextInt(list.size()));
    }
}

/**
 * Your RandomizedCollection object will be instantiated and called as such:
 * RandomizedCollection obj = new RandomizedCollection();
 * boolean param_1 = obj.insert(val);
 * boolean param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */
python cartopy绘制扇形区域图/cartopy绘制北极部分区域 实际上,这个问题原因还是由于投影转换的问题,在set_extend时,绘制的上下边界仍然是方形、未被正确投影的边界,与我们的set_boundary存在冲突,最根本的原因还是在于cartopy对于投影计算的一些缺陷。另外我们需要指出的是:**该方法不适用于极地投影,即NorthPolarStereo,由于NorthPolarStereo本身投影特性只需一个参数,本身并不适合。我们绘制极地投影时,同样也是使用set_boundary绘制圆形边界,那么当我们想要绘制扇形时,可以通过。请根据喜好自行选择, 阅读详情

相关推荐

51单片机独立按键控制LED(二)

对于机械开关,当机械触点断开、闭合时,由于机械触点的弹性作用,一个开关在闭合时不会马上稳定地接通,在断开时也不会一下子断开,所以在开关闭合及断开的瞬间会伴随一连串的抖动。独立按键控制LED显示二进制。独立按键控制LED灯亮灭。独立按键控制LED状态。独立按键控制LED移位。

m0_50562428的博客 5352

LeetCode 每日一题381:O(1) 时间插入、删除和获取随机元素 - 允许重复

381.O(1) 时间插入、删除和获取随机元素 - 允许重复 设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构。 注意: 允许出现重复元素。 insert(val):向集合中插入元素 val。 remove(val):当 val 存在时,从集合中移除一个 val。 getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。 示例: // 初始化一个空的集合。 RandomizedCollection collection = new R

雷震子的博客 441

OPENSSL使用方法

预备知识KEY 通常指私钥。CSR 是 Certificate Signing Request 的缩写,即证书签名请求,这不是证书,只是包含申请证书的基本信息。生成证书时要把这个提交给权威的证书颁发机构,颁发机构审核通过之后,再根据这些申请信息生成相应的证书。CRT 即 certificate的缩写,即证书。 X.509 是一种证书格式。对X.509证书来说,认证者总是CA或由CA指定的人,一份...

zxm8513CSDN博客 1185

常数时间插入、删除和获取随机元素

常数时间插入、删除和获取随机元素 实现RandomizedSet 类: RandomizedSet() 初始化 RandomizedSet 对象 bool insert(int val) 当元素 val 不存在时,向集合中插入该项,并返回 true ;否则,返回 false 。 bool remove(int val) 当元素 val 存在时,从集合中移除该项,并返回 true ;否则,返回 false 。 int getRandom() 随机返回现有集合中的一项(测试用例保证调用此方法时集合中至少存在一个

weixin_51447387的博客 279

LeetCode //C++ - 381. Insert Delete GetRandom O(1) - Duplicates allowed

【代码】LeetCode //C++ - 381. Insert Delete GetRandom O(1) - Duplicates allowed

Made in Code 820

Leetcode381 场周赛题解

Leetcode381 场周赛题解

ProgramNovice的博客 1990

LeetCode O(1)时间插入、删除和获取随机元素 - 允许重复

设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构。 注意: 允许出现重复元素。 insert(val):向集合中插入元素 val。 remove(val):当 val 存在时,从集合中移除一个 val。 getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。 示例: // 初始化一个空的集合。 RandomizedColle...

hestyle的博客 1305

LeetcodeInsert Delete GetRandom O(1) - Duplicates allowed

题目链接:https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/ 题目: Design a data structure that supports all following operations in average O(1) time. Note: Duplicate elemen

业精于勤,荒于嬉 2907

LeetCode381 Insert Delete GetRandom O(1) - Duplicates allowed

this is the follow up of Leetcode380, which allows dupliciate values added in item pool. if you recall the solution we use to solve LC380, list and hashmap used in that. and list stores the elements and hashmap stores the value and its index as k-v pair. s

Tech in Pieces 376

<leetcode>381. Insert Delete GetRandom O(1) - Duplicates allowed

381. Insert Delete GetRandom O(1) - Duplicates allowed Design a data structure that supports all following operations in average O(1) time. Note: Duplicate elements are allowed insert(val): In

Vipin_Pei的博客 868

LeetCode - 381. Insert Delete GetRandom O(1) - Duplicates allowed(允许重复)

LeetCode - 381. Insert Delete GetRandom O(1) - Duplicates allowed(允许重复) 题目链接 题目 解析 做这题之前先做LeetCode - 380。 这一题加上了可以加入重复的元素,题目就变得复杂了一些。 大体思路还是使用HashMap + ArrayList,只不过Map是HashMap&amp;lt;Integer, ArrayList...

zxzxin的博客~ 505

leetcode381. Insert Delete GetRandom O(1) - Duplicates allowed

题目要求 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 c...

weixin_34389926的博客 153

[leetcode] 381. Insert Delete GetRandom O(1) - 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):...

Learning from the mistakes 356

LeetCode381. Insert Delete GetRandom O(1) - Duplicates allowed

Insert Delete GetRandom O(1) - Duplicates allowed 思路:java中的list提供了针对制定元素删除的方法以及判断该元素是否存在的方法 GitHub地址:https://github.com/corpsepiges/leetcode 目前java版本的答案大约进度是免费的差40题,python大约是一半,其他的等以后再

徐玄清的专栏 1157

Leetcode381. Insert Delete GetRandom O(1) - Duplicates Allowed

添加操作并不难,在删除的时候,避免错误的方法是,先判断要删除的数是否恰好等于list的最后一个数,如果是,那么很好删除;如果不是,那就确定了要删除的数和list最后一个数不一样,这时候就可以将本题看待成Duplicates not allowed的情形了,做哈希表的修改就不会出错。1、添加一个数,如果原本存在则返回false,否则返回true。注意,即使已经存在也要添加;2、删除一个数,如果原本不存在则返回false,否则返回true;3、随机返回一个数,每个数的返回的概率应该与其出现的频次成正比。

数学、算法爱好者的博客 727

LeetCode381场周赛个人题解

这次周赛怎么又是两道一样的题

EQUINOX1的博客 1178

O(1) 时间插入、删除和获取随机元素 - 允许重复

题面描述 基本思路 o(1)决定了使用数组和哈希表功能 class RandomizedCollection { public: /** Initialize your data structure here. */ unordered_map<int, unordered_set<int>> idx;//unordered_的底层实现是哈希表 vector<int> nums;//存数 RandomizedCollection() {

qq_40493829的博客 328

381. Insert Delete GetRandom O(1) - Duplicates allowed

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...

学习应该是一个长链接 137

LeetCode 381. O(1) 时间插入、删除和获取随机元素 - 允许重复

设计一个支持在平均时间复杂度O(1)下,执行以下操作的数据结构。 注意: 允许出现重复元素。 insert(val):向集合中插入元素 val。 remove(val):当 val 存在时,从集合中移除一个 val。 getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。 示例: // 初始化一个空的集合。 RandomizedCollection collection = new RandomizedCollection(); // 向集...

韩旭051的博客 801

LeetCode:381 Insert Delete GetRandom O(1)

381. Insert Delete GetRandom O(1) - Duplicates allowed Design a data structure that supports all following operations in average O(1) time. Note: Duplicate elements are allowed.

Wisimer 1140

[LeetCode] 381.O(1) 时间插入、删除和获取随机元素 - 允许重复(Hard)C语言题解

题目 设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构。 注意: 允许出现重复元素。 insert(val):向集合中插入元素 val。 remove(val):当 val 存在时,从集合中移除一个 val。 getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。 示例 ①示例1 说明 ①数据范围(自测) -214...

wjy的博客 514

自动泊车APA-遥控泊车RPA系统功能规范

自动泊车遥控泊车系统功能规范

YOLOv11行李箱目标检测数据集-618张-标注类别为行李箱.zip

1. YOLO目标检测数据集, 适用于YOLOV5、yolov7,yolov8, yolov11, yolov13, yolo26等系列算法,含标签,已标注好,可以直接用来训练;2. 内置data.yaml数据集配置文件,已经划分好了训练集、验证集等;3. 数据集和模型具体情况可参考https://blog.csdn.net/zhiqingAI/article/details/161091291?spm=1011.2415.3001.5331 , 和 https://blog.csdn.net/zhiqingAI/article/details/124230743?spm=1001.2014.3001.5502

上一篇: Leetcode 380. Insert Delete GetRandom O(1) 常数增删改系统 解题报告
下一篇: Leetcode 400. Nth Digit 第n个数字 解题报告
学术状态抽奖器
博客等级 码龄14年 249粉丝 270原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值