<Random> 380 381(hard) 138
380. Insert Delete GetRandom O(1)
class RandomizedSet {
ArrayList<Integer> nums;
HashMap<Integer, Integer> locs;
Random rand = new Random();
/** Initialize your data structure here. */
public RandomizedSet() {
nums = new ArrayList<Integer>();
locs = new HashMap<Integer, Integer>();
} /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
boolean contain = locs.containsKey(val);
if( contain ) return false;
locs.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 contain = locs.containsKey(val);
if( !contain ) return false;
int loc = locs.get(val);
if(loc < nums.size() - 1){// not the last one than swap the last one with this val
int lastOneVal = nums.get(nums.size() - 1);
nums.set(loc, lastOneVal);
locs.put(lastOneVal, loc);
}
locs.remove(val);
nums.remove(nums.size() - 1);
return true;
} /** Get a random element from the set. */
public int getRandom() {
return nums.get(rand.nextInt(nums.size()));
}
}
381. Insert Delete GetRandom O(1) - Duplicates allowed
之前那道题不能有重复数字,而这道题可以有,那么就不能像之前那道题那样建立每个数字和其坐标的映射了,但是我们可以建立数字和其所有出现位置的集合之间的映射,虽然写法略有不同,但是思路和之前那题完全一样,都是将数组最后一个位置的元素和要删除的元素交换位置,然后删掉最后一个位置上的元素。对于 insert 函数,我们将要插入的数字在 nums 中的位置加入 m[val] 数组的末尾,然后在数组 nums 末尾加入 val,我们判断是否有重复只要看 m[val] 数组只有刚加的 val 一个值还是有多个值。remove 函数是这题的难点,我们首先看 HashMap 中有没有 val,没有的话直接返回 false。然后我们取出 nums 的尾元素,把尾元素 HashMap 中的位置数组中的最后一个位置更新为 m[val] 的尾元素,这样我们就可以删掉 m[val] 的尾元素了,如果 m[val] 只有一个元素,那么我们把这个映射直接删除。然后将 nums 数组中的尾元素删除,并把尾元素赋给 val 所在的位置,注意我们在建立 HashMap 的映射的时候需要用堆而不是普通的 vector 数组,因为我们每次 remove 操作后都会移除 nums 数组的尾元素,如果我们用 vector 来保存数字的坐标,而且只移出末尾数字的话,有可能出现前面的坐标大小超过了此时 nums 的大小的情况,就会出错,所以我们用优先队列对所有的相同数字的坐标进行自动排序,每次把最大位置的坐标移出即可
class RandomizedCollection {
List<Integer> nums;
Map<Integer, Set<Integer>> map;
java.util.Random random; /** Initialize your data structure here. */
public RandomizedCollection() {
nums = new ArrayList<>();
map = new HashMap<>();
random = new 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 doesContain = map.containsKey(val);
if(!doesContain) map.put(val, new HashSet<>());
map.get(val).add(nums.size());
nums.add(val);
return !doesContain;
} /** 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;
if(!map.get(val).contains(nums.size() - 1)){
int curPos = map.get(val).iterator().next();
int lastVal = nums.get(nums.size() - 1);
map.get(lastVal).remove(nums.size() - 1);
map.get(lastVal).add(curPos);
map.get(val).remove(curPos);
map.get(val).add(nums.size() - 1);
nums.set(curPos, lastVal);
}
map.get(val).remove(nums.size() - 1);
if(map.get(val).isEmpty()) map.remove(val);
nums.remove(nums.size() - 1);
return true;
} /** Get a random element from the collection. */
public int getRandom() {
return nums.get(random.nextInt(nums.size()));
}
}
138. Copy List with Random Pointer
用map<Node, Node>的形式将旧节点和新节点进行映射。
第一个循环先复制val数值,第二个循环复制next和random节点。
class Solution {
public Node copyRandomList(Node head) {
if(head == null) return null;
Map<Node, Node> map = new HashMap<>();
Node cur = head;
//loop 1. copy all the nodes
while(cur != null){
map.put(cur, new Node(cur.val, null, null));
cur = cur.next;
}
//loop2. assign next ad random pointers
cur = head;
while(cur != null){
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
return map.get(head);
}
}
<Random> 380 381(hard) 138的更多相关文章
- 【转】python之random模块分析(一)
[转]python之random模块分析(一) random是python产生伪随机数的模块,随机种子默认为系统时钟.下面分析模块中的方法: 1.random.randint(start,stop): ...
- Random Erasing Augmentation(REA)
为了增强模型的泛化的性能,一般的手段有数据增强和正则化方法(如dropout,BN),而用于数据增强的一般方法有:随机裁剪.随机水平翻转.平移.旋转.增加噪音和生成网络方法等(前两个方法用的最多,也最 ...
- Day13 Python基础之time/datetime/random模块一(十一)
time模块 import time print(help(time)) time.time() #return current time in seconds since the Epoch as ...
- python之random模块分析(一)
random是python产生伪随机数的模块,随机种子默认为系统时钟.下面分析模块中的方法: 1.random.randint(start,stop): 这是一个产生整数随机数的函数,参数start代 ...
- Python 常用方法和模块的使用(time & datetime & os &random &sys &shutil)-(六)
1 比较常用的一些方法 1.eval()方法:执行字符串表达式,并返回到字符串. 2.序列化:变量从内存中变成可存储或传输到文件或变量的过程,可以保存当时对象的状态,实现其生命周期的延长,并且需要时可 ...
- 异常检测算法Robust Random Cut Forest(RRCF)关键定理引理证明
摘要:RRCF是亚马逊发表的一篇异常检测算法,是对周志华孤立森林的改进.但是相比孤立森林,具有更为扎实的理论基础.文章的理论论证相对较为晦涩,且没给出详细的证明过程.本文不对该算法进行详尽的描述,仅对 ...
- 【LeetCode】138. Copy List with Random Pointer 复制带随机指针的链表 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人公众号:负雪明烛 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https:/ ...
- js 常用函数收集(基础)
(1).判断是否为数值 function isNum(obj){ return !isNaN(parseFloat(obj)) && isFinite(obj); } (2).判断是否 ...
- DOS程序员手册(一)
当今MS-Windows横扫大江南北,让我们这就来研究一下它的祖宗——MS-DOS! 这本书很难得,希望读者好好学习! DOS程序员手册(一) DOS教程 (以下内容全部为原作者的阐述,照样保留) 这 ...
随机推荐
- word设置标题1,标题2,标题3项目编号联动
word经常要按层级显示标题,并且标题样式之间要联动 如: 设置办法: word内鼠标右键 2.选择项目符号和编号 3.选择一个样式并自定义 将级别链接到样式.选择对应标题样式即可实现联动.
- 明解C语言 入门篇 第十三章答案
练习13-1 /* 打开与关闭文件 */ #include <stdio.h> int main(void) { ]; FILE* fp; printf("请输入你要打开的文件& ...
- Springboot2 Metrics之actuator集成influxdb, Grafana提供监控和报警
到目前为止,各种日志收集,统计监控开源组件数不胜数,即便如此还是会有很多人只是tail -f查看一下日志文件.随着容器化技术的成熟,日志和metrics度量统计已经不能仅仅靠tail -f来查看了,你 ...
- sc命令创建和删除服务
安装服务 sc create 服务名 binPath= "C:\Users\Administrator\Desktop\win32srvDemo\win32srvdemo\Debug\win ...
- SpringBoot自定义注解、AOP打印日志
前言 在SpringBoot中使用自定义注解.aop切面打印web请求日志.主要是想把controller的每个request请求日志收集起来,调用接口.执行时间.返回值这几个重要的信息存储到数据库里 ...
- Java引用类型原理深度剖析,看完文章,90%的人都收藏了
本文为synchronized系列第二篇.主要内容为分析偏向锁的实现. 偏向锁的诞生背景和基本原理在上文中已经讲过了. 本文将分为几块内容: 1.偏向锁的入口 2.偏向锁的获取流程 3.偏向锁的撤销流 ...
- Python基础23(习惯)
自己写的大段代码,注释分为两种: 一种 # 顶格写,为后注释," Ctrl+/ " 一种为边写边注释
- 浅谈 Flask 框架
一.框架对比 Django —— 教科书式框架 优势:组件全,功能全,教科书 劣势:占用资源,创建复杂度高 Flask —— 以简单为基准开发,一切从简,能省则省 优势:轻,块 劣势:先天不足,第三方 ...
- 使用Composer安装阿里云短信失败
安装步骤 请参考以下步骤,使用Composer安装依赖. 如果在您的系统上全局安装Composer,您可以在项目目录中运行以下内容,将 Alibaba Cloud Client for PHP 添加为 ...
- AutoLayout的使用
虽然苹果提供了AutoresizingMask的布局方式,这个方式局限性太大:只能解决父控件和子控件间的相对关系: 因此,推出了AutoLayout:苹果官方也是推荐开发者尽量使用autolayout ...