380. Insert Delete GetRandom O(1)
经过昨天的消沉

今天我振作了

设计个数据结构,添加,删除,随机获取都是O(1).
怎么会有这么牛逼的数据结构,所以肯定相应的要耗费空间。
添加和获取耗时O(1)是Array的特性,或者说是Map/Table的特性,思考下php的array就明白其实是index的mapping了。
Random要求O(1)那就是需要知道数据结构的大小,并且保证储存的元素是相邻的。
其实就是一个table/map,KEY是添加的元素,value是他储存在array中的位置;
然后一个array和上面的table/map对应;
再一个变量size记录总共有多少个元素,便于random.
添加,直接添加到SIZE的位置,MAP里记录,SIZE++
RANDOM,通过SIZE随便RANDOM一个数,直接从ARRAY里直接获取。
删除,为了保证所有元素在ARRAY中是相邻的,像LIST那样。用ARRAY模拟就是删除之后,后面所有的都前移,但是要求O(1),可以把最后一个元素和它换一下。换的时候相应的改变MAP/TABLE里的信息,删除map里本来最后一个KEY(因为我们换到前面了),最后SIZE--,使得array[size]指向的位置虽然不为空,但是是标记为删除的元素,就是刚才换过来的,而RANDOM不会影响。
感觉和学习哦啊以前做过的用JAVA实现PHP ARRAY的作业有点像,只不过那个要自己写hash function
为了图省事不resize array,用了arrayList,但是意思是那个意思。。
public class RandomizedSet {
Map<Integer,Integer> map;
List<Integer> list;
int size;
/** Initialize your data structure here. */
public RandomizedSet()
{
map = new HashMap<Integer,Integer>();
list = new ArrayList<Integer>();
this.size = 0;
}
/** 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;
else
{
list.add(size,val);
map.put(val,size++);
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;
else if(size == 0) map.remove(val);
else
{
int tailKey = list.get(size-1);
map.put(tailKey,map.get(val));
list.set(map.get(val),tailKey);
size--;
map.remove(val);
}
return true;
}
/** Get a random element from the set. */
public int getRandom()
{
Random rdm = new Random();
return list.get(rdm.nextInt(size));
}
}
二刷。
用个Map,KEY是存的元素,VAL是元素存在arraylist里的位置。
删除是把arraylist里最后一个有效元素和删除的元素调换,同时修改map里被最后一个有效元素(key)的相应位置(value)。。
public class RandomizedSet {
List<Integer> list;
int num;
Map<Integer, Integer> map;
/** Initialize your data structure here. */
public RandomizedSet() {
list = new ArrayList<>();
num = 0;
map = new HashMap<>();
}
/** 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;
} else {
list.add(num, val);
map.put(val, num++);
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;
} else if (num == 0) {
map.remove(val);
return true;
} else {
int removedIndex = map.get(val);
int backElement = list.get(num - 1);
map.put(backElement, removedIndex);
list.set(removedIndex, backElement);
num--;
map.remove(val);
return true;
}
}
/** Get a random element from the set. */
public int getRandom() {
Random rdm = new Random();
return list.get(rdm.nextInt(num));
}
}
380. Insert Delete GetRandom O(1)的更多相关文章
- 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) 解题报告(Python)
[LeetCode]380. Insert Delete GetRandom O(1) 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxu ...
- [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]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 ...
- 380. Insert Delete GetRandom O(1) 设计数据结构:在1的时间内插入、删除、产生随机数
[抄题]: Design a data structure that supports all following operations in average O(1) time. insert(va ...
- LeetCode 380. Insert Delete GetRandom O(1) 常数时间插入、删除和获取随机元素(C++/Java)
题目: Design a data structure that supports all following operations in averageO(1) time. insert(val): ...
- [LC] 380. Insert Delete GetRandom O(1)
Design a data structure that supports all following operations in average O(1) time. insert(val): In ...
随机推荐
- Android 自定义View实现单击和双击事件
自定义View, 1. 自定义一个Runnable线程TouchEventCountThread , 用来统计500ms内的点击次数 2. 在MyView中的 onTouchEvent 中调用 上面 ...
- redis的安装-windows和linux
windows 下载地址:http://code.google.com/p/servicestack/wiki/RedisWindowsDownload 下载解压到D盘下: 进到该目录下,有下列文件: ...
- java 文件类操作(转载)
11.3 I/O类使用 由于在IO操作中,需要使用的数据源有很多,作为一个IO技术的初学者,从读写文件开始学习IO技术是一个比较好的选择.因为文件是一种常见的数据源,而且读写文件也是程序员进行IO编程 ...
- 普及下Oracle hints语法
普及下Oracle hints的语法:{DELETE|INSERT|SELECT|UPDATE} /*+ hint [text] [hint[text]]... */ 1.hint只能出现在诸如sel ...
- 总结iframe高度自适应,自适应子页面高度
在网上找了很多iframe的高度自适应,发现很多兼容性都不是很好,于是自己总结了一下. 页面html节点上要有 <!DOCTYPE html PUBLIC "-//W3C//DTD ...
- CT 来值班,让您安心过新年!
春节,盼了整整一年的节日,我们一定要抛开工作,狠狠的开心,狠狠的幸福,但是作为苦逼的运维,你们真的能完全抛开工作(对网站不闻不问)吗?OneAPM CT 24 小时监控您的网站,让您无忧无虑过新年. ...
- POJ 2886 Who Gets the Most Candies?(反素数+线段树)
点我看题目 题意 :n个小盆友从1到n编号按顺时针编号,然后从第k个开始出圈,他出去之后如果他手里的牌是x,如果x是正数,那下一个出圈的左手第x个,如果x是负数,那出圈的是右手第-x个,游戏中第p个离 ...
- 发现一个Doxygen风格的QT帮助
http://cep.xray.aps.anl.gov/software/qt4-x11-4.8.6-browser/classes.html http://cep.xray.aps.anl.gov/ ...
- Android Studio 使用笔记:Git 的配置和第一次提交到仓库
Git客户端网址:http://git-scm.com/download/ 根据自己的使用平台下载对应的客户端.这里以Mac系统为例,当客户端软件安装配置完毕后,打开AS的配置面板,找到Git的选项 ...
- android使用tabhost实现导航
参考 http://blog.csdn.net/xixinyan/article/details/6771341 http://blog.sina.com.cn/s/blog_6b04c8eb0101 ...