[leetcode]380. Insert Delete GetRandom O(1)常数时间插入删除取随机值
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();
Solution1: HashMap + ArrayList
1. use an ArrayList together with HashMap, making hashmap save key(item)->value(idx)
2. To reverse item in O(1), avoiding traversal the whole arrayList in O(n) time, we swap the toDelete item with last item in the list
3. Go through an example like this:

use HashMap to get removeIdx:

Set the last item in the list as replaceValue, why the last item? In order to maintain other indices.

Deal with HashMap: (1) put (2)delete

Deal with List: (1) set (2)delete

code:
class RandomizedSet {
Map<Integer, Integer> map;
List<Integer> list;
Random r; // java 自带类
/** Initialize your data structure here. */
public RandomizedSet() {
list = new ArrayList<>();
map = new HashMap<>();
r = 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) {
/**
hashmap
30 - 0
40 - 1
50 - 2
60 - 3
list: 30 40 50 60
0 1 2 3
**/
if (!map.containsKey(val)) return false;
int removeIdx = map.get(val); // Idx: 1
int replaceValue = list.get(list.size()-1); // replaceValue : 60
// deal with map
map.put(replaceValue, removeIdx);
map.remove(val);
// deal with list
list.set(removeIdx, replaceValue);
list.remove(list.size() -1);
return true;
}
/** Get a random element from the set. */
public int getRandom() {
return list.get(r.nextInt(list.size()));
}
}
[leetcode]380. Insert Delete GetRandom 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) 常数时间插入、删除和获取随机元素(C++/Java)
题目: Design a data structure that supports all following operations in averageO(1) time. insert(val): ...
- [leetcode]381. Insert Delete GetRandom O(1) - Duplicates allowed常数时间插入删除取随机值
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)时间 - 允许重复
Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...
- [LeetCode] 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) 插入删除获得随机数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)
380. Insert Delete GetRandom O(1) Add to List Description Submission Solutions Total Accepted: 21771 ...
- 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 ...
随机推荐
- USG防火墙DHCP设置保留IP地址
在使用disp cur查看当前配置 然后使用undo修改 这样10.0.1.1网段到10.0.1.100之间的IP地址不会分出去
- phpcms调用语句
title 标题:url 链接地址:thumb缩略图 :先调用moreinfo="1" content 内容: {php list($copyfrom) = explode('| ...
- Hadoop 权限管理
Hadoop的权限管理同Linux的很像,有用户,用户组之分,同时Hadoop提供了权限管理命令,主要包括: chmod [-R] mode file … 只有文件的所有者或者超级用户才有权限改变文件 ...
- Android之ListView动态添加数据(SQLiteOpenHelper类添加数据)
一.SQLiteOpenHelper类: 这次我们通过sqlite来动态添加数据,接下来我们创建一个openHelper.java,在前面sqlite博客中我们已经详细的讲了SQLite的创建及使用等 ...
- 报错:NoSuchMethodError: kafka.javaapi.PartitionMetadata.leader()Lkafka/cluster/Broker;
报错现象: 在pom文件添加: <dependency> <groupId>org.apache.kafka</groupId> <artifactId> ...
- Scrapy学习篇(九)之文件与图片下载
Media Pipeline Scrapy为下载item中包含的文件(比如在爬取到产品时,同时也想保存对应的图片)提供了一个可重用的 item pipelines . 这些pipeline有些共同的方 ...
- C++Primer第五版——习题答案详解(二)
习题答案目录:https://www.cnblogs.com/Mered1th/p/10485695.html 第3章 字符串.向量和数组 练习3.2 一次读入一整行 #include<iost ...
- 使用 JavaScript 将 XML 转成 JSON
function xmlToJson(xml) { // Create the return object var obj = {}; if (xml.nodeType == 1) { // elem ...
- 导出Excel(Ext 前台部分)
开发思路: - 序列化当前GridPanel 数据, 表头结构(用于对应关系), 通过控制器Aspose写到Excel中, 然后返回临时文件地址, 弹出窗口下载. function btnExport ...
- import_module 导入变量的包
遇到你想导入的包是变量的时候,可以用这个实现 from importlib import import_module settings_path = self.pathm2 = import_modu ...