经过昨天的消沉

今天我振作了

设计个数据结构,添加,删除,随机获取都是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)的更多相关文章

  1. LeetCode 380. Insert Delete GetRandom O(1)

    380. Insert Delete GetRandom O(1) Add to List Description Submission Solutions Total Accepted: 21771 ...

  2. 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). ...

  3. 【LeetCode】380. Insert Delete GetRandom O(1) 解题报告(Python)

    [LeetCode]380. Insert Delete GetRandom O(1) 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxu ...

  4. [LeetCode] 380. Insert Delete GetRandom O(1) 常数时间内插入删除和获得随机数

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

  5. [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 ...

  6. [leetcode]380. Insert Delete GetRandom O(1)常数时间插入删除取随机值

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

  7. LeetCode 380. Insert Delete GetRandom O(1) (插入删除和获得随机数 常数时间)

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

  8. 380. Insert Delete GetRandom O(1) 设计数据结构:在1的时间内插入、删除、产生随机数

    [抄题]: Design a data structure that supports all following operations in average O(1) time. insert(va ...

  9. LeetCode 380. Insert Delete GetRandom O(1) 常数时间插入、删除和获取随机元素(C++/Java)

    题目: Design a data structure that supports all following operations in averageO(1) time. insert(val): ...

  10. [LC] 380. Insert Delete GetRandom O(1)

    Design a data structure that supports all following operations in average O(1) time. insert(val): In ...

随机推荐

  1. DOS命令中出现空格问题

    1.DOS命令中路径出现空格时如何处理? 在DOS命令中,如果路径中出现空格,可能为报错:如参数错误 如:  xcopy C:\ABC CD\txt.txt C:\ ,   由于路径中包含空格,执行后 ...

  2. 防止apche列出目录以及下载文件

    1.修改httpd.conf,将override none改为override all 2.在需要设置权限的目录上传.htaccess文件,.htaccess文件内容如下: <FilesMatc ...

  3. 以中断方式实现1s定时

    中断方式比较特殊,需要使用单片机内部的中断处理机制,同时指定中断函数. #include <reg52.h> sbit LED = P0^; unsigned ; void main() ...

  4. Using .NET 4's Lazy<T> 实现单实例

    Using .NET 4's Lazy<T> type Explanation of the following code: If you're using .NET 4 (or high ...

  5. 在ubuntu12.0.4上搭建samba服务器以实现文件共享

    在安装之前samba服务器之前,先进行以下配置和测试. <壹> 准备工作 一.NAT联网方式 (1)硬件连接 无需网线,无需路由器 (2)虚拟机选择NAT连接方式 (3)测试网络通不通 在 ...

  6. Web负载均衡的几种方式

    Web负载均衡的几种实现方式 摘要:负载均衡(Load Balance)是集群技术(Cluster)的一种应用.负载均衡可以将工作任务分摊到多个处理单元,从而提高并发处理能力.目前最常见的负载均衡应用 ...

  7. 除了判断语句if switch 我们还可以怎么做?-b

    之前项目中有根据后台数据执行不同代码,根据不同的字符串返回不同UIViewController对象,最开始需要的vc 种类不多我用的是if else 做字符串比较再执行不同代码,但是如果需求的vc 有 ...

  8. WordPress 前端投稿/编辑插件 DJD Site Post(支持游客和已注册用户)

    转自:http://www.wpdaxue.com/front-end-publishing.html 说到前端用户投稿,倡萌之前推荐过3个不错的插件: WordPress匿名投稿插件:DX-Cont ...

  9. 被windows“折磨”了一个礼拜

    说是被windows折磨了一个礼拜,这话一点都不假!由于想彻底的卸载SQL Server而误删系统文件,导致系统重启之后持续蓝屏.无奈之下只能重装系统(心想,加入当初自己将系统备份的话,那该是多美好的 ...

  10. bzoj 2401: 陶陶的难题I 数论

    2401: 陶陶的难题I Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 89  Solved: 24[Submit][Status] Descript ...