当前位置:网站首页>LeetCode - 380 O(1) 时间插入、删除和获取随机元素 (设计 哈希表+数组)
LeetCode - 380 O(1) 时间插入、删除和获取随机元素 (设计 哈希表+数组)
2022-07-25 15:32:00 【三岁就很萌@D】


哈希表+list


class RandomizedSet {
//将值放入list中 为了可以随机取数
private List<Integer> list;
//map的key是值 map的val是 值在list中的位置
//为了方便在o(1)时间内 插入删除值
private Map<Integer,Integer> map;
public RandomizedSet() {
list = new ArrayList<>();
map = new HashMap<>();
}
public boolean insert(int val) {
//如果该值已经存在了
if(map.containsKey(val) == true)
return false;
else{
//新添加值的index
int index = list.size();
//添加至list
list.add(val);
//添加至map
map.put(val,index);
return true;
}
}
public boolean remove(int val) {
//val不存在 删除失败
if(map.containsKey(val) == false)
return false;
else{
//list最后一个数的下标
int lasti = list.size()-1;
//list最后一个数的值
int lastv = list.get(lasti);
//val 在list中的下标
int vali = map.get(val);
//将list的最后一个数放在val在list的位置上
list.set(vali,lastv);
//修改list的最后一个数在map中的下标
map.put(lastv,vali);
//删除list中的最后一个数
list.remove(lasti);
//在map中删除val
map.remove(val);
return true;
}
}
public int getRandom() {
int n = list.size();
//产生0 - n-1范围的随机整数
return list.get((int)(Math.random()*n));
}
}
/** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */
边栏推荐
- 伤透脑筋的CPU 上下文切换
- Singleton mode 3-- singleton mode
- 《图书馆管理系统——“借书还书”模块》项目研发阶段性总结
- matlab 优化工具 manopt 安装
- window系统黑窗口redis报错20Creating Server TCP listening socket *:6379: listen: Unknown error19-07-28
- Notes on inputview and inputaccessoryview of uitextfield
- MySQL优化总结二
- JVM garbage collector details
- pageHelper不生效,sql没有自动加上limit
- 使用cpolar建立一个商业网站(如何购买域名)
猜你喜欢

分布式原理 - 什么是分布式系统

小波变换--dwt2 与wavedec2

No tracked branch configured for branch xxx or the branch doesn‘t exist. To make your branch trac

理解“平均负载”

Get the ask code corresponding to the key pressed by the keyboard

Delayed loading source code analysis:

Pytorch学习笔记-刘二老师RNN高级篇-代码注释及结果

Gary Marcus: 学习语言比你想象的更难

matlab 优化工具 manopt 安装

JVM—类加载器和双亲委派模型
随机推荐
Cf685b find the center of gravity of each subtree of a rooted tree
SQL cultivation manual from scratch - practical part
Pat grade a 1151 LCA in a binary tree (30 points)
Week303 of leetcode
ML - Speech - advanced speech model
图论及概念
Xcode添加mobileprovision证书文件报错:Xcode encountered an error
Pytorch学习笔记--SEResNet50搭建
2019 Shaanxi Provincial race K-variant Dijstra
C # fine sorting knowledge points 10 generic (recommended Collection)
JVM dynamic bytecode technology details
MATLAB 如何生产随机复序列
ML - 自然语言处理 - 自然语言处理简介
Binary complement
MySQL优化总结二
HDU3873-有依赖的最短路(拓扑排序)
2019 Shaanxi provincial competition j-bit operation + greed
C#精挑整理知识要点11 委托和事件(建议收藏)
Endnote 添加中文GBT7714样式 word中如何引用文献
GAMES101复习:变换