Insert Delete GetRandom O(1) I & II
Design a data structure that supports all following operations in 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.
分析:
因为要求所有操作O(1),插入可以满足这个条件,如果用数组来存储值,getRandom可以满足O(1).但是要求不能重复和delete的时候也满足这个条件,只能使用一个map. key是值,value是位置。
public class RandomizedSet {
ArrayList<Integer> nums;//值
// value to position
HashMap<Integer, Integer> valueToPositionMap;
Random rand;
public RandomizedSet() {
nums = new ArrayList<>();
valueToPositionMap = new HashMap<>();
rand = new Random(System.currentTimeMillis());
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
boolean isContained = valueToPositionMap.containsKey(val);
if ( isContained ) return false;
valueToPositionMap.put( val, nums.size());
nums.add(val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
boolean isContained = valueToPositionMap.containsKey(val);
if ( ! isContained ) return false;
int position = valueToPositionMap.get(val);
if (position != nums.size() - ) {
// put the true last one to 'position' in nums
int lastOne = nums.get(nums.size() - );
nums.set( position , lastOne );
valueToPositionMap.put(lastOne, position);
}
valueToPositionMap.remove(val);
nums.remove(nums.size() - );
return true;
}
/** Get a random element from the set. */
public int getRandom() {
return nums.get( rand.nextInt(nums.size()) );
}
}
第二种情况:允许有重复数值。
用set来记录同一个值出现的位置,如果被删除的数不是最后一个,则和最后一个换一下位置,然后删除就可以了。
public class RandomizedCollection {
List<Integer> nums;
Map<Integer, Set<Integer>> valueToPositionMap;
Random rand;
public RandomizedCollection() {
nums = new ArrayList<>();
valueToPositionMap = new HashMap<>();
rand = new Random(System.currentTimeMillis());
}
/**
* Inserts a value to the collection. Returns true if the collection did not
* already contain the specified element.
*/
public boolean insert(int val) {
boolean isContained = valueToPositionMap.containsKey(val);
if (!isContained) {
valueToPositionMap.put(val, new HashSet<>());
}
valueToPositionMap.get(val).add(nums.size());
nums.add(val);
return !isContained;
}
/**
* Removes a value from the collection. Returns true if the collection contained
* the specified element.
*/
public boolean remove(int val) {
if (!valueToPositionMap.containsKey(val)) {
return false;
}
if (!valueToPositionMap.get(val).contains(nums.size() - )) {
int currPos = valueToPositionMap.get(val).iterator().next();
int lastVal = nums.get(nums.size() - );
valueToPositionMap.get(lastVal).remove(nums.size() - );
valueToPositionMap.get(lastVal).add(currPos);
valueToPositionMap.get(val).remove(currPos);
valueToPositionMap.get(val).add(nums.size() - );
nums.set(currPos, lastVal);
}
valueToPositionMap.get(val).remove(nums.size() - );
if (valueToPositionMap.get(val).isEmpty()) {
valueToPositionMap.remove(val);
}
nums.remove(nums.size() - );
return true;
}
/** Get a random element from the collection. */
public int getRandom() {
return nums.get(rand.nextInt(nums.size()));
}
}
Insert Delete GetRandom O(1) I & II的更多相关文章
- [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] 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)
380. Insert Delete GetRandom O(1) Add to List Description Submission Solutions Total Accepted: 21771 ...
- 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] 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) 插入删除获得随机数O(1)时间
Design a data structure that supports all following operations in average O(1) time. insert(val): In ...
- [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 ...
随机推荐
- fork与vfork
先看一个fork的例子: ; int main(void) { int var, pid; ; ) { printf("vfork error"); exit(-); } ) { ...
- struts.xml框架
1.首先在.jsp文件中<form action="/项目名称/login" method="post"> 2.然后浏览器会访问struts.xml ...
- jquery报错Uncaught ReferenceError: $ is not defined
- 如何更好地利用Pmd、Findbugs和CheckStyle分析结果
这里列出了很多Java静态分析工具,每一种工具关注一个特定的能发挥自己特长的领域,我们可以列举一下: Pmd 它是一个基于静态规则集的Java源码分析器,它可以识别出潜在的如下问题:– 可能的bug— ...
- OCS 开放缓存服务
开放缓存服务( Open Cache Service,简称OCS)是在线缓存服务,为热点数据的访问提供高速响应.说白了,就是一款基于memcached开发的对外云缓存服务器,完全可以把OCS当成mem ...
- sql server cpu占用过高优化
SQLSERVER排查CPU占用高的情况 今天中午,有朋友叫我帮他看一下数据库,操作系统是Windows2008R2 ,数据库是SQL2008R2 64位 64G内存,16核CPU 硬件配置还是比较高 ...
- [译]ASP.NET 5: New configuration files and containers
原文:http://gunnarpeipman.com/2014/11/asp-net-5-new-configuration-files-and-containers/ ASP.NET vNext提 ...
- Python网络socket学习
Python 网络编程 Python 提供了两个级别访问的网络服务.: 低级别的网络服务支持基本的 Socket,它提供了标准的 BSD Sockets API,可以访问底层操作系统Socket接口的 ...
- Unix时间戳转换怎样在Excel批量修改?
最近在操作项目的时候碰到一个Unix时间戳转换的问题."date_time":1393031347这个是什么,你知道吗?如果你对Unix时间戳了解的话一眼就看出来.但我们本着科普的 ...
- Spark之scala
一.什么是scala scala 是基于JVMde 编程语言.JAVA是运行在jvm上的编程语言,java 源代码通过jvm被编译成class 文件,然后在os上运行class 文件.scala是运行 ...