每天一道Rust-LeetCode(2019-06-14)
每天一道Rust-LeetCode(2019-06-14) 常数时间插入、删除和获取随机元素
坚持每天一道题,刷题学习Rust.
题目描述
https://leetcode-cn.com/problems/insert-delete-getrandom-o1/
设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。
insert(val):当元素 val 不存在时,向集合中插入该项。
remove(val):元素 val 存在时,从集合中移除该项。
getRandom:随机返回现有集合中的一项。每个元素应该有相同的概率被返回。
示例 :
// 初始化一个空的集合。
RandomizedSet randomSet = new RandomizedSet();
// 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomSet.insert(1);
// 返回 false ,表示集合中不存在 2 。
randomSet.remove(2);
// 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomSet.insert(2);
// getRandom 应随机返回 1 或 2 。
randomSet.getRandom();
// 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomSet.remove(1);
// 2 已在集合中,所以返回 false 。
randomSet.insert(2);
// 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。
randomSet.getRandom();
解题过程
思路:1.用slice存值,用map保存值在slice中的index;
2.每次删除时,为了避免移动元素,用数组末尾元素覆盖需要删除的元素,然后删除数组末尾元素;
extern crate rand;
use rand::Rng;
use std::collections::HashMap;
use std::collections::HashSet;
struct RandomizedSet {
m: HashMap<i32, usize>,
v: Vec<i32>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl RandomizedSet {
/** Initialize your data structure here. */
fn new() -> Self {
RandomizedSet {
m: HashMap::new(),
v: Vec::new(),
}
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
pub fn insert(&mut self, val: i32) -> bool {
if self.m.contains_key(&val) {
return false;
}
let i = self.m.len();
if self.v.len() > i {
//经过删除以后v里面空间可能非常富裕,直接用现有的才对
self.v[i] = val;
} else {
self.v.push(val);
}
self.m.insert(val, i);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
pub fn remove(&mut self, val: i32) -> bool {
if !self.m.contains_key(&val) {
return false;
}
let i = *self.m.get(&val).expect("must ok");
if i != self.m.len() - 1 {
//如果是最后一个,就不用调整了
self.v[i] = self.v[self.m.len() - 1]; //最后一个值填充到i
self.m.insert(self.v[i], i);
}
self.m.remove(&val);
return true;
}
/** Get a random element from the set. */
pub fn get_random(&self) -> i32 {
let mut rng = rand::thread_rng();
let mut i: usize = rng.gen();
i = i % self.m.len();
return self.v[i];
}
}
一点感悟
rust标准库中居然没有随机数生成器.
其他
欢迎关注我的github,本项目文章所有代码都可以找到.
每天一道Rust-LeetCode(2019-06-14)的更多相关文章
- http://www.cnblogs.com/huangcong/archive/2010/06/14/1757957.html
http://www.cnblogs.com/huangcong/archive/2010/06/14/1757957.html http://www.cnblogs.com/langtianya/a ...
- 每日一练ACM 2019.04.14
2019.4.14 第1001题:Sum Problem Problem DescriptionHey, welcome to HDOJ(Hangzhou Dianzi University Onli ...
- BlackArch Linux 2019.06.01 宣布发布
导读 BlackArch Linux是一个基于Arch Linux的发行版,专为渗透测试人员和安全研究人员设计,并包含大量渗透测试和安全实用程序,已宣布发布2019.06.01版本. BlackArc ...
- [每日一题2020.06.14]leetcode #70 爬楼梯 斐波那契数列 记忆化搜索 递推通项公式
题目链接 题意 : 求斐波那契数列第n项 很简单一道题, 写它是因为想水一篇博客 勾起了我的回忆 首先, 求斐波那契数列, 一定 不 要 用 递归 ! 依稀记得当年校赛, 我在第一题交了20发超时, ...
- 黄聪:如何使用CodeSmith批量生成代码(转:http://www.cnblogs.com/huangcong/archive/2010/06/14/1758201.html)
先看看CodeSmith的工作原理: 简单的说:CodeSmith首先会去数据库获取数据库的结构,如各个表的名称,表的字段,表间的关系等等,之后再根据用户自定义好的模板文件,用数据库结构中的关键字替代 ...
- 2014.06.14 GlusterFS技术交流视频
6月14线下GlusterFS视频交流.高清视频是非常好的,我初听言论方面,谈到迅速,似乎不是很清楚,讲座结束后速度需要改进.谢谢能力的天空AbleSky高大内设,谢谢学生参加. 在线公开课:http ...
- Murano Weekly Meeting 2016.06.14
Meeting time: 2016.June.14 1:00~2:00 Chairperson: Kirill Zaitsev, from Mirantis Meeting summary: 1. ...
- 2019.03.14 ZJOI2019模拟赛 解题报告
得分: \(100+100+0=200\)(\(T1\)在最后\(2\)分钟写了出来,\(T2\)在最后\(10\)分钟写了出来,反而\(T3\)写了\(4\)个小时爆\(0\)) \(T1\):风王 ...
- 2019.06.17课件:[洛谷P1310]表达式的值 题解
P1310 表达式的值 题目描述 给你一个带括号的布尔表达式,其中+表示或操作|,*表示与操作&,先算*再算+.但是待操作的数字(布尔值)不输入. 求能使最终整个式子的值为0的方案数. 题外话 ...
- leetCode练题——14. Longest Common Prefix
1.题目 14. Longest Common Prefix Write a function to find the longest common prefix string amongst a ...
随机推荐
- ORB-SLAM2 地图保存
一.简介 在ORB-SLAM2的System.h文件中,有这样一句话:// TODO: Save/Load functions,让读者自己实现地图的保存与加载功能.其实在应用过程中很多场合同样需要先保 ...
- 生成git的SSH公钥
1.右键,点击 git bash here 2.安装成功后设置用户和邮箱git config --global user.name "name"git config --glob ...
- 海边拾贝-F-第三方项目
第三方网站,不定期更新: 陈浩个人博客: https://coolshell.cn/ 阮一峰个人博客:http://www.ruanyifeng.com/blog/2015/02/make.html ...
- 使用App.Metrics监控消息队列
使用App.Metrics监控消息队列 一.简介 App Metrics是一个开放源代码和跨平台的.NET库,用于记录应用程序中的指标.App Metrics可以在.NET Core或也支持.NET ...
- java.sql.SQLException: Could not establish connection to 192.168.8.111:10000/default: java.net.ConnectException: Connection refused: connect at org.apache.hadoop.hive.jdbc.HiveConnection.<init>(HiveC
java.sql.SQLException: Could not establish connection to 192.168.8.111:10000/default: java.net.Conne ...
- 关于全局异常(@ControllerAdvice)的学习与思考
一声梧叶一声秋,一点芭蕉一点愁,三更归梦三更后.____徐再思<水仙子·夜雨> 今天的主题是全局异常的构建,处理,以及一些小细节: 至于全局异常的代码构建以及一些常用的异常处理类可以看这篇 ...
- 【大数据】SparkSql 连接查询中的谓词下推处理 (一)
本文首发于 vivo互联网技术 微信公众号 https://mp.weixin.qq.com/s/YPN85WBNcnhk8xKjTPTa2g 作者:李勇 目录: 1.SparkSql 2.连接查询和 ...
- vuex源码分析(二) state及strict属性 详解
state也就是vuex里的值,也即是整个vuex的状态,而strict和state的设置有关,如果设置strict为true,那么不能直接修改state里的值,只能通过mutation来设置 例1: ...
- CodeForces 574D Bear and Blocks
Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n ...
- Python 简单爬虫案例
Python 简单爬虫案例 import requests url = "https://www.sogou.com/web" # 封装参数 wd = input('enter a ...