Leetcode: 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 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();
The idea is to add a set to the hashMap to remember all the locations of a duplicated number.
public class RandomizedCollection {
HashMap<Integer, HashSet<Integer>> map;
ArrayList<Integer> arr;
java.util.Random random; /** Initialize your data structure here. */
public RandomizedCollection() {
map = new HashMap<Integer, HashSet<Integer>>();
arr = new ArrayList<Integer>();
random = new java.util.Random();
} /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
boolean res = false;
if (!map.containsKey(val)) {
map.put(val, new HashSet<Integer>());
res = true;
}
arr.add(val);
map.get(val).add(arr.size()-1);
return res;
} /** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
if (!map.containsKey(val)) return false;
int lastItem = arr.get(arr.size()-1);
int index = arr.size()-1;
if (lastItem != val) {
HashSet<Integer> lastItemSet = map.get(lastItem);
index = map.get(val).iterator().next();
arr.set(index, lastItem);
lastItemSet.remove(arr.size()-1);
lastItemSet.add(index);
} if (map.get(val).size() == 1) map.remove(val);
else map.get(val).remove(index);
arr.remove(arr.size()-1);
return true;
} /** Get a random element from the collection. */
public int getRandom() {
return arr.get(random.nextInt(arr.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();
*/
Leetcode: Insert Delete GetRandom O(1) - Duplicates allowed的更多相关文章
- [LeetCode] Insert Delete GetRandom O(1) - Duplicates allowed 常数时间内插入删除和获得随机数 - 允许重复
Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...
- 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). ...
- 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 常数时间内插入删除和获得随机数 - 允许重复
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 381. Insert Delete GetRandom O(1) - Duplicates allowed
原题链接在这里:https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/?tab=Description ...
- 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 ...
- 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常数时间插入删除取随机值
Design a data structure that supports all following operations in average O(1) time. Note: Duplicate ...
随机推荐
- linux下php-fpm 启动参数及重要配置
约定几个目录 /usr/local/php/sbin/php-fpm/usr/local/php/etc/php-fpm.conf/usr/local/php/etc/php.iniI. php-fp ...
- 9.PHP内核探索:通过mod_php5支持PHP
Apache对PHP的支持是通过Apache的模块mod_php5来支持的.如果希望Apache支持PHP的话,在./configure步 骤需要指定--with-apxs2=/usr/local/a ...
- 关于Java中File的renameTo函数
先看Java编程实战经典中的一道习题: 编写程序,程序运行时输入目录名称,并把该目录下的所有文件名后缀修改成.txt. 按照题意,我在d盘新建了文件夹test,并在该文件夹下新建了一个文件file.d ...
- Linux的权限说明
Linux的权限不是很细致,只有RWX三种r(Read,读取):对文件而言,具有读取文件内容的权限:对目录来说,具有浏览目录的权限.w(Write,写入):对文件而言,具有新增,修改,删除文件内容的权 ...
- 估值十亿美元、1.5亿用户,公司CEO却跑路了
转载这篇文章是觉得配图非常好玩的,文章的真实性有待证明 年收益3600万美元的.曾经拥有高口碑产品的Evernote,却正在把一手好牌打烂,距离IPO越来越远,屡屡被业界唱衰. "独角兽公司 ...
- php学习笔记 [预定义数组(超全局数组)]
<?php 预定义数组: * 自动全局变量---超全局数组 * * 1.包含了来自WEB服务器,客户端,运行环境和用户输入的数据 * 2.这些数组比较特别 * 3.全局范围内自动生效,都可以直 ...
- mysql import data slow solution---overview information
1 SELECT SUM(DATA_LENGTH)+SUM(INDEX_LENGTH) FROM information_schema.tables WHERE TABLE_SCHEMA='dat ...
- lua环境安装 转
curl -R -O http://www.lua.org/ftp/lua-5.2.2.tar.gz tar zxf lua-5.2.2.tar.gz cd lua-5.2.2 make linux ...
- 20145211 《Java程序设计》第1周学习总结——小荷才露尖尖角
教材学习内容总结 Java语言概述 Java是SUN1995年推出的一门高级编程语言,完全面向对象,安全可靠,具有跨平台性(用其编写的语言在任何系统上都能运行,只需安装一个JVM) Java三大平台包 ...
- The Bip Buffer - The Circular Buffer with a Twist
Introduction The Bip-Buffer is like a circular buffer, but slightly different. Instead of keeping on ...