LeetCode 380. Insert Delete GetRandom O(1)
380. Insert Delete GetRandom O(1)
Description Submission Solutions
- Total Accepted: 21771
- Total Submissions: 56175
- Difficulty: Medium
- Contributors: Admin
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();
Subscribe to see which companies asked this question.
【题目分析】
设计一种数据结构,使得插入,删除和随机获取一个值的时间复杂度为O(1).
【思路】
1. 随机读取一个数的话,使用数组的时间复杂度是最小的,因为通过下标可以直接定位。考虑到元素会不断插入,我们可以选择ArrayList来存储我们的元素。
2. 要删除一个元素,在数组中需要遍历才能找到这个元素。而在HashMap中,可以快速定位一个元素。因此我们可以用HashMap来存储元素和它在ArrayList中对应的下标。
通过以上的分析,我们知道了数据结构该如何设计。
【java代码】
public class RandomizedSet {
Map<Integer, Integer> map;
List<Integer> list;
Random random; /** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<>();
list = new ArrayList<>();
random = new Random();
} /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(map.containsKey(val)) return false;
map.put(val, list.size());
list.add(val);
return true;
} /** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(!map.containsKey(val)) return false;
int loc = map.get(val);
if(loc < list.size()-1) {
int last = list.get(list.size()-1);
list.set(loc, last);
map.put(last, loc);
}
map.remove(val);
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 RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
LeetCode 380. Insert Delete GetRandom O(1)的更多相关文章
- [LeetCode] 380. Insert Delete GetRandom O(1) 插入删除获得随机数O(1)时间
Design a data structure that supports all following operations in average O(1) time. insert(val): In ...
- leetcode 380. Insert Delete GetRandom O(1) 、381. Insert Delete GetRandom O(1) - Duplicates allowed
380. Insert Delete GetRandom O(1) 实现插入.删除.获得随机数功能,且时间复杂度都在O(1).实际上在插入.删除两个功能中都包含了查找功能,当然查找也必须是O(1). ...
- [LeetCode] 380. Insert Delete GetRandom O(1) 常数时间内插入删除和获得随机数
Design a data structure that supports all following operations in average O(1) time. insert(val): In ...
- LeetCode 380. Insert Delete GetRandom O(1) (插入删除和获得随机数 常数时间)
Design a data structure that supports all following operations in average O(1) time. insert(val): In ...
- [leetcode]380. Insert Delete GetRandom O(1)常数时间插入删除取随机值
Design a data structure that supports all following operations in average O(1) time. insert(val): In ...
- LeetCode 380. Insert Delete GetRandom O(1) 常数时间插入、删除和获取随机元素(C++/Java)
题目: Design a data structure that supports all following operations in averageO(1) time. insert(val): ...
- [leetcode]380. Insert Delete GetRandom O(1)设计数据结构,实现存,删,随机取的时间复杂度为O(1)
题目: Design a data structure that supports all following operations in average O(1) time.1.insert(val ...
- [LeetCode] 381. Insert Delete GetRandom O(1) - Duplicates allowed 插入删除和获得随机数O(1)时间 - 允许重复
Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...
- LeetCode 381. Insert Delete GetRandom O(1) - Duplicates allowed O(1) 时间插入、删除和获取随机元素 - 允许重复(C++/Java)
题目: Design a data structure that supports all following operations in averageO(1) time. Note: Duplic ...
随机推荐
- POJ1269:Intersecting Lines(判断两条直线的关系)
题目:POJ1269 题意:给你两条直线的坐标,判断两条直线是否共线.平行.相交,若相交,求出交点. 思路:直线相交判断.如果相交求交点. 首先先判断是否共线,之后判断是否平行,如果都不是就直接求交点 ...
- gcc __attribute__
GNU C 的一大特色就是__attribute__ 机制.__attribute__ 可以设置函数属性(Function Attribute ).变量属性(Variable Attribute )和 ...
- HTML5笔记——formData
注:formData中的数据在控制台上的console里面是打印不出来的,只能在控制台的network里面查看到具体的发送数据和发送选项 文章出处:梦想天空 XMLHttpRequest Level ...
- Python(socket编程——1、理论)
Socket的英文原义是“孔”或“插座”.作为BSD UNIX的进程通信机制,取后一种意思.通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,可以用来实现不同虚拟机 ...
- PL/SQL编程-介绍
pl/sql是一种编程语言,就像java一样java叫做高级编程语言 什么是编程,编程说到底就是对于数据的操作,数据包括数据库存储的和自己定义的变量常量等等数据,对他们进行逻辑化的处理 以实现特定的功 ...
- Problem A. Array Factory XVII Open Cup named after E.V. Pankratiev Stage 4: Grand Prix of SPb, Sunday, Octorber 9, 2016
思路: 直接二分长度不可行,因为有负数. 考虑枚举坐便删l个数,那如果可以在短时间内求出符合条件的右边最小删的数的个数,这题便可做了. 即:当左边删l个数时,要使sum[n]-sum[l]-fsum[ ...
- PHP开发之apache mac上配置
我使用的Mac OS X版本是10.8.2,Mac自带了Apache环境. 启动Apache 设置虚拟主机 启动Apache 打开“终端(terminal)”,输入 sudo apachectl -v ...
- WeX5基础
最近在研究微信app开发,使用的是WeX5,在这里把一些基础知识点记录下来,忘记了可以翻阅查看. 一:开发后端服务 1.建立数据源:窗口--首选项--studio配置--数据源--增加--数据源类型选 ...
- LigerUI ligerComboBox 下拉框 表格 多选无效
$("#txt1").ligerComboBox({ width: 250, slide: false, selectBoxWidth: 500, selectBoxHeight: ...
- Python基本数据类型之列表
学习Python的列表类型需要了解和掌握什么是列表.列表的可变性.列表的访问.列表的增删改查等操作~ 1.了解列表 list1 = ['abc', 123, {1, 2, 3},[2,3]] Pyth ...