LeetCode 经典 150 · 可视化
逐步动画、变量流转与五语言代码参考
#380 · 数组 / 字符串
O(1) 时间插入、删除和获取随机元素
Insert Delete GetRandom O(1)
insert(1), remove(2), insert(2), getRandom()状态流5 个关键状态
步骤 1插入 1,并记录 index[1]=0。
values=[1], index={1:0}状态 11
→状态 2·
→状态 3·
推荐
数组 + 哈希索引
时间
平均 O(1)空间 O(n)哈希表定位下标;删除时用末尾元素覆盖目标,再弹出末尾。
1class RandomizedSet {2 constructor() {3 this.values = [];4 this.index = new Map();5 }6 insert(x) {7 if (this.index.has(x)) return false;8 this.index.set(x, this.values.length);9 this.values.push(x);10 return true;11 }12 remove(x) {13 if (!this.index.has(x)) return false;14 const i = this.index.get(x),15 last = this.values.at(-1);16 this.values[i] = last;17 this.index.set(last, i);18 this.values.pop();19 this.index.delete(x);20 return true;21 }22 getRandom() {23 return this.values[Math.floor(Math.random() * this.values.length)];24 }25}多语言参考
来源 · CC BY-SA 4.0 ↗Java · C++ · Go
这是一组同题正确实现,独立于上方当前动画方法;不同语言可能采用另一种正确策略。
1class RandomizedSet {2 private Map<Integer, Integer> d = new HashMap<>();3 private List<Integer> q = new ArrayList<>();4 private Random rnd = new Random();5 6 public RandomizedSet() {7 }8 9 public boolean insert(int val) {10 if (d.containsKey(val)) {11 return false;12 }13 d.put(val, q.size());14 q.add(val);15 return true;16 }17 18 public boolean remove(int val) {19 if (!d.containsKey(val)) {20 return false;21 }22 int i = d.get(val);23 d.put(q.get(q.size() - 1), i);24 q.set(i, q.get(q.size() - 1));25 q.remove(q.size() - 1);26 d.remove(val);27 return true;28 }29 30 public int getRandom() {31 return q.get(rnd.nextInt(q.size()));32 }33}34 35/**36 * Your RandomizedSet object will be instantiated and called as such:37 * RandomizedSet obj = new RandomizedSet();38 * boolean param_1 = obj.insert(val);39 * boolean param_2 = obj.remove(val);40 * int param_3 = obj.getRandom();41 */交互式算法学习
从执行步骤真正理解 LeetCode 经典 150
本站整理 150 道高频算法面试题和 302 种解法。动画方法同步展示 JavaScript 与 Python;每题另提供 Java、C++ 与 Go 同题参考实现。