当前位置:网站首页>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(); */
边栏推荐
- Idea eye care settings
- Pytorch框架练习(基于Kaggle Titanic竞赛)
- 二进制补码
- The difference between Apple buy in and apple pay
- Take you to create your first C program (recommended Collection)
- ML - 图像 - 深度学习和卷积神经网络
- 数据系统分区设计 - 分区与二级索引
- 2021上海市赛-B-排序后dp
- 获取键盘按下的键位对应ask码
- No tracked branch configured for branch xxx or the branch doesn‘t exist. To make your branch trac
猜你喜欢
随机推荐
2016 CCPC network trial c-change root DP good question
Pat class a topic directory
2019陕西省省赛K-变种Dijstra
Binary complement
Deadlock gossip
伤透脑筋的CPU 上下文切换
Submarine cable detector tss350 (I)
2021 Shanghai match-b-ranked DP
MATLAB读取显示图像时数据格式转换原因
ML - natural language processing - Basics
Application of C language array in Sanzi chess -- prototype of Queen n problem
C#精挑整理知识要点9 集合2(建议收藏)
CF365-E - Mishka and Divisors,数论+dp
盒子躲避鼠标
CF685B-求有根树每颗子树的重心
PageHelper does not take effect, and SQL does not automatically add limit
获取键盘按下的键位对应ask码
分布式原理 - 什么是分布式系统
Cf365-e - Mishka and divisors, number theory +dp
Idea - click the file code to automatically synchronize with the directory









