https://leetcode.cn/problems/FortPu/
题目要求
设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构:
insert(val):当元素 val 不存在时返回 true ,并向集合中插入该项,否则返回 false 。
remove(val):当元素 val 存在时返回 true ,并从集合中移除该项,否则返回 false 。
getRandom:随机返回现有集合中的一项。每个元素应该有 相同的概率 被返回。
方法:Hash表+线性表
- 使用hash表来存储val和对应的index下标,同时可以使用containsKey来判断是某个元素已经存在
- 使用线性表来保存元素,元素和下标是一一对应的
List<Integer> list;
Map<Integer, Integer> map;
Random rd;
/** Initialize your data structure here. */
public RandomizedSet() {
list = new ArrayList<>();
map = new HashMap<>();
rd = new Random();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
// val已存在
if (map.containsKey(val)) return false;
// 插入
int index = list.size();
list.add(val);
map.put(val, index);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if (!map.containsKey(val)) return false;
int index = map.get(val);// 获取删除元素下标
int n = list.size() - 1;
int last = list.get(n);// 获取最后一个元素
list.set(index, last);// 最后一个元素覆盖删除元素
map.put(last, index);// last的index是删除元素的index
list.remove(n);// 删除最后一个元素
map.remove(val);// 删除map中的val
return true;
}
/** Get a random element from the set. */
public int getRandom() {
return list.get(rd.nextInt(list.size()));
}