24
24
</strong >RandomizedSet randomSet = new RandomizedSet(); // 初始化一个空的集合
25
25
randomSet.insert(1); // 向集合中插入 1 , 返回 true 表示 1 被成功地插入
26
26
27
- randomSet.remove(2); // 返回 false,表示集合中不存在 2
27
+ randomSet.remove(2); // 返回 false,表示集合中不存在 2
28
28
29
- randomSet.insert(2); // 向集合中插入 2 返回 true ,集合现在包含 [1,2]
29
+ randomSet.insert(2); // 向集合中插入 2 返回 true ,集合现在包含 [1,2]
30
30
31
- randomSet.getRandom(); // getRandom 应随机返回 1 或 2
32
-
33
- randomSet.remove(1); // 从集合中移除 1 返回 true 。集合现在包含 [2]
31
+ randomSet.getRandom(); // getRandom 应随机返回 1 或 2
34
32
35
- randomSet.insert(2 ); // 2 已在集合中,所以返回 false
33
+ randomSet.remove(1 ); // 从集合中移除 1 返回 true 。集合现在包含 [2]
36
34
37
- randomSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2
35
+ randomSet.insert(2); // 2 已在集合中,所以返回 false
36
+
37
+ randomSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2
38
38
</pre >
39
39
40
40
<p >  ; </p >
@@ -56,22 +56,115 @@ randomSet.getRandom(); // 由于 2 是集合中唯一的数字,getRandom 总
56
56
57
57
<!-- 这里可写通用的实现逻辑 -->
58
58
59
+ “哈希表 + 动态列表”实现。
60
+
61
+ 哈希表存放每个元素的值和对应的下标,而动态列表在每个下标位置存放每个元素。由动态列表实现元素的随机返回。
62
+
63
+ 注意,在 ` remove() ` 实现上,将列表的最后一个元素设置到待删元素的位置上,然后删除最后一个元素,这样在删除元素的时候,不需要挪动一大批元素,从而实现 ` O(1) ` 时间内操作。
64
+
59
65
<!-- tabs:start -->
60
66
61
67
### ** Python3**
62
68
63
69
<!-- 这里可写当前语言的特殊实现逻辑 -->
64
70
65
71
``` python
66
-
72
+ class RandomizedSet :
73
+ def __init__ (self ):
74
+ """
75
+ Initialize your data structure here.
76
+ """
77
+ self .a = []
78
+ self .m = {}
79
+
80
+ def insert (self , val : int ) -> bool :
81
+ """
82
+ Inserts a value to the set. Returns true if the set did not already contain the specified element.
83
+ """
84
+ if val in self .m:
85
+ return False
86
+ self .m[val] = len (self .a)
87
+ self .a.append(val)
88
+ return True
89
+
90
+ def remove (self , val : int ) -> bool :
91
+ """
92
+ Removes a value from the set. Returns true if the set contained the specified element.
93
+ """
94
+ if val in self .m:
95
+ idx = self .m[val]
96
+ self .a[idx], self .a[- 1 ] = self .a[- 1 ], self .a[idx]
97
+ self .m[self .a[idx]] = idx
98
+ self .a.pop()
99
+ del self .m[val]
100
+ return True
101
+ return False
102
+
103
+ def getRandom (self ) -> int :
104
+ """
105
+ Get a random element from the set.
106
+ """
107
+ return random.choice(self .a)
108
+
109
+
110
+ # Your RandomizedSet object will be instantiated and called as such:
111
+ # obj = RandomizedSet()
112
+ # param_1 = obj.insert(val)
113
+ # param_2 = obj.remove(val)
114
+ # param_3 = obj.getRandom()
67
115
```
68
116
69
117
### ** Java**
70
118
71
119
<!-- 这里可写当前语言的特殊实现逻辑 -->
72
120
73
121
``` java
74
-
122
+ class RandomizedSet {
123
+ private final Map<Integer , Integer > m;
124
+ private final List<Integer > a;
125
+
126
+ /* * Initialize your data structure here. */
127
+ public RandomizedSet () {
128
+ this . m = new HashMap<> ();
129
+ this . a = new ArrayList<> ();
130
+ }
131
+
132
+ /* * Inserts a value to the set. Returns true if the set did not already contain the specified element. */
133
+ public boolean insert (int val ) {
134
+ if (this . m. containsKey(val)) {
135
+ return false ;
136
+ }
137
+ this . m. put(val, this . a. size());
138
+ this . a. add(val);
139
+ return true ;
140
+ }
141
+
142
+ /* * Removes a value from the set. Returns true if the set contained the specified element. */
143
+ public boolean remove (int val ) {
144
+ if (this . m. containsKey(val)) {
145
+ int idx = this . m. get(val), last = this . a. size() - 1 ;
146
+ Collections . swap(this . a, idx, last);
147
+ this . m. put(this . a. get(idx), idx);
148
+ this . a. remove(last);
149
+ this . m. remove(val);
150
+ return true ;
151
+ }
152
+ return false ;
153
+ }
154
+
155
+ /* * Get a random element from the set. */
156
+ public int getRandom () {
157
+ return this . a. get(ThreadLocalRandom . current(). nextInt(this . a. size()));
158
+ }
159
+ }
160
+
161
+ /**
162
+ * Your RandomizedSet object will be instantiated and called as such:
163
+ * RandomizedSet obj = new RandomizedSet();
164
+ * boolean param_1 = obj.insert(val);
165
+ * boolean param_2 = obj.remove(val);
166
+ * int param_3 = obj.getRandom();
167
+ */
75
168
```
76
169
77
170
### ** ...**
0 commit comments