当前位置:网站首页>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(); */
边栏推荐
- Are you ready to break away from the "involution circle"?
- No tracked branch configured for branch xxx or the branch doesn‘t exist. To make your branch trac
- No tracked branch configured for branch xxx or the branch doesn‘t exist. To make your branch trac
- 2019浙江省赛C-错排问题,贪心
- Pytorch框架练习(基于Kaggle Titanic竞赛)
- 2021 Shanghai sai-d-cartland number variant, DP
- Phased summary of the research and development of the "library management system -" borrowing and returning "module
- 你准备好脱离“内卷化怪圈”了吗?
- ML - natural language processing - Key Technologies
- UIDocumentInteractionController UIDocumentPickerViewController
猜你喜欢

wait()和sleep()的区别理解

PAT甲级1152 Google Recruitment (20 分)

Brain racking CPU context switching

获取键盘按下的键位对应ask码

Graph theory and concept

盒子躲避鼠标

Games101 review: 3D transformation

ML - Speech - advanced speech model

Cf888g clever dictionary tree + violent divide and conquer (XOR minimum spanning tree)

Node learning
随机推荐
死锁杂谈
matlab---错误使用 var 数据类型无效。第一个输入参数必须为单精度值或双精度值
Word 样式模板复制到另一文档
Understanding the difference between wait() and sleep()
Ml speech depth neural network model
JVM garbage collector details
Pytorch学习笔记-Advanced_CNN(Using Inception_Module)实现Mnist数据集分类-(注释及结果)
Reflection - Notes
2021hncpc-e-difference, thinking
ML - 图像 - 深度学习和卷积神经网络
Brain racking CPU context switching
2019陕西省省赛J-位运算+贪心
2016 CCPC network trial c-change root DP good question
ML - 自然语言处理 - 关键技术
The development summary of the function of fast playback of audio and video in any format on the web page.
GAMES101复习:变换
LeetCode - 622 设计循环队列 (设计)
PAT甲级1151 LCA in a Binary Tree (30 分)
数据系统分区设计 - 分区与二级索引
CF888G-巧妙字典树+暴力分治(异或最小生成树)