Skip to content

Commit f499024

Browse files
author
lucifer
committed
1 parent f19a7a8 commit f499024

File tree

2 files changed

+144
-0
lines changed

2 files changed

+144
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@ leetcode 题解,记录自己的 leetcode 解题之路。
213213
- [0334.increasing-triplet-subsequence](./problems/334.increasing-triplet-subsequence.md)
214214
- [0365.water-and-jug-problem](./problems/365.water-and-jug-problem.md)
215215
- [0378.kth-smallest-element-in-a-sorted-matrix](./problems/378.kth-smallest-element-in-a-sorted-matrix.md)
216+
- [0380.insert-delete-getrandom-o1](./problems/380.insert-delete-getrandom-o1.md)🆕
216217
- [0416.partition-equal-subset-sum](./problems/416.partition-equal-subset-sum.md)
217218
- [0445.add-two-numbers-ii](./problems/445.add-two-numbers-ii.md)
218219
- [0454.4-sum-ii](./problems/454.4-sum-ii.md)
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
## 题目地址(380. 常数时间插入、删除和获取随机元素)
2+
3+
https://leetcode-cn.com/problems/insert-delete-getrandom-o1/description/
4+
5+
## 题目描述
6+
7+
```
8+
设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。
9+
10+
insert(val):当元素 val 不存在时,向集合中插入该项。
11+
remove(val):元素 val 存在时,从集合中移除该项。
12+
getRandom:随机返回现有集合中的一项。每个元素应该有相同的概率被返回。
13+
示例 :
14+
15+
// 初始化一个空的集合。
16+
RandomizedSet randomSet = new RandomizedSet();
17+
18+
// 向集合中插入 1 。返回 true 表示 1 被成功地插入。
19+
randomSet.insert(1);
20+
21+
// 返回 false ,表示集合中不存在 2 。
22+
randomSet.remove(2);
23+
24+
// 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
25+
randomSet.insert(2);
26+
27+
// getRandom 应随机返回 1 或 2 。
28+
randomSet.getRandom();
29+
30+
// 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
31+
randomSet.remove(1);
32+
33+
// 2 已在集合中,所以返回 false 。
34+
randomSet.insert(2);
35+
36+
// 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。
37+
randomSet.getRandom();
38+
39+
```
40+
41+
## 思路
42+
43+
这是一个设计题。这道题的核心就是考察基本数据结构和算法的操作以及复杂度。
44+
45+
我们来回顾一下基础知识:
46+
47+
- 数组支持随机访问,其按照索引查询的时间复杂度为$O(1)$,按值查询的时间复杂度为$O(N)$, 而插入和删除的时间复杂度为$O(N)$。
48+
- 链表不支持随机访问,其查询的时间复杂度为$O(N)$,但是对于插入和删除的复杂度为$O(1)$(不考虑找到选要处理的节点花费的时间)。
49+
- 对于哈希表,正常情况下其查询复杂度平均为$O(1)$,插入和删除的复杂度为$O(1)$。
50+
51+
由于题目要求 getRandom 返回要随机,那么如果单纯使用链表以及哈希表肯定是不行的。而又由于对于插入和删除我们也需要平均复杂度为$O(1)$,因此单纯使用数组也是不行的。我们考虑多种使用数据结构来实现。
52+
53+
> 实际上 LeetCode 设计题,几乎没有单纯一个数据结构搞定的,基本都需要多种数据结构结合,这个时候需要你对各种数据结构以及其基本算法的复杂度有着清晰的认知。
54+
55+
对于 getRandom 用数组很简单。对于判断是否已经有了存在的元素,我们使用哈希表也很容易做到。因此我们将数组随机访问,以及哈希表$O(1)$按值检索的特性结合起来,即同时使用这两种数据结构。
56+
57+
对于删除和插入,我们需要一些技巧。
58+
59+
对于插入:
60+
61+
- 我们直接往 append,并将其插入哈希表即可。
62+
- 对于删除,我们需要做到 O(1)。删除哈希表很明显可以,但是对于数组,平均时间复杂度为 O(1)。
63+
64+
因此如何应付删除的这种性能开销呢? 我们知道对于数据删除,我们的时间复杂度来源于
65+
66+
1. `查找到要删除的元素`
67+
2. 以及`重新排列被删除元素后面的元素`
68+
69+
对于 1,我们可以通过哈希表来实现。 key 是插入的数字,value 是数组对应的索引。删除的时候我们根据 key 反查出索引就可以快速找到。
70+
71+
对于 2,我们可以通过和数组最后一项进行交换的方式来实现,这样就避免了数据移动。同时数组其他项的索引仍然保持不变,非常好!
72+
73+
> 相应的我们插入的时候,需要维护哈希表
74+
75+
## 关键点解析
76+
77+
- 数组
78+
- 哈希表
79+
- 数组 + 哈希表
80+
- 基本算法时间复杂度分析
81+
82+
## 代码
83+
84+
```python
85+
from random import random
86+
87+
88+
class RandomizedSet:
89+
90+
def __init__(self):
91+
"""
92+
Initialize your data structure here.
93+
"""
94+
self.data = dict()
95+
self.arr = []
96+
self.n = 0
97+
98+
def insert(self, val: int) -> bool:
99+
"""
100+
Inserts a value to the set. Returns true if the set did not already contain the specified element.
101+
"""
102+
if val in self.data:
103+
return False
104+
self.data[val] = self.n
105+
self.arr.append(val)
106+
self.n += 1
107+
108+
return True
109+
110+
def remove(self, val: int) -> bool:
111+
"""
112+
Removes a value from the set. Returns true if the set contained the specified element.
113+
"""
114+
if val not in self.data:
115+
return False
116+
i = self.data[val]
117+
# 更新data
118+
self.data[self.arr[-1]] = i
119+
self.data.pop(val)
120+
# 更新arr
121+
self.arr[i] = self.arr[-1]
122+
# 删除最后一项
123+
self.arr.pop()
124+
self.n -= 1
125+
126+
return True
127+
128+
def getRandom(self) -> int:
129+
"""
130+
Get a random element from the set.
131+
"""
132+
133+
return self.arr[int(random() * self.n)]
134+
135+
136+
# Your RandomizedSet object will be instantiated and called as such:
137+
# obj = RandomizedSet()
138+
# param_1 = obj.insert(val)
139+
# param_2 = obj.remove(val)
140+
# param_3 = obj.getRandom()
141+
```
142+
143+
## 相关题目

0 commit comments

Comments
 (0)