Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 85beeb5

Browse files
committed
feat: add solutions to lc problem: No.0381. Insert Delete Get Random O(1) - Duplicates allowed
1 parent bf65776 commit 85beeb5

File tree

5 files changed

+333
-65
lines changed

5 files changed

+333
-65
lines changed

‎solution/0300-0399/0380.Insert Delete GetRandom O(1)/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ randomSet.getRandom();
5050

5151
哈希表存放每个元素的值和对应的下标,而动态列表在每个下标位置存放每个元素。由动态列表实现元素的随机返回。
5252

53-
注意,在 `remove()` 的时候,先将列表的最后一个元素设置到待删元素的位置上,然后删除最后一个元素,这样在删除元素的时候,不需要挪动一大批元素,从而实现 `O(1)` 时间内操作。
53+
注意,在 `remove()` 实现上,将列表的最后一个元素设置到待删元素的位置上,然后删除最后一个元素,这样在删除元素的时候,不需要挪动一大批元素,从而实现 `O(1)` 时间内操作。
5454

5555
<!-- tabs:start -->
5656

‎solution/0300-0399/0381.Insert Delete GetRandom O(1) - Duplicates allowed/README.md‎

Lines changed: 118 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,27 +40,142 @@ collection.remove(1);
4040
collection.getRandom();
4141
</pre>
4242

43-
4443
## 解法
4544

4645
<!-- 这里可写通用的实现逻辑 -->
4746

47+
"哈希表 + 动态列表"实现。
48+
49+
哈希表存放每个元素的值和对应的下标集合,而动态列表在每个下标位置存放每个元素。由动态列表实现元素的随机返回。
50+
51+
注意,在 `remove()` 实现上,将列表的最后一个元素设置到待删元素的位置上,然后删除最后一个元素,这样在删除元素的时候,不需要挪动一大批元素,从而实现 `O(1)` 时间内操作。
52+
4853
<!-- tabs:start -->
4954

5055
### **Python3**
5156

5257
<!-- 这里可写当前语言的特殊实现逻辑 -->
5358

5459
```python
55-
60+
class RandomizedCollection:
61+
62+
def __init__(self):
63+
"""
64+
Initialize your data structure here.
65+
"""
66+
self.m = {}
67+
self.l = []
68+
69+
def insert(self, val: int) -> bool:
70+
"""
71+
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
72+
"""
73+
idx_set = self.m.get(val, set())
74+
idx_set.add(len(self.l))
75+
self.m[val] = idx_set
76+
self.l.append(val)
77+
return len(idx_set) == 1
78+
79+
def remove(self, val: int) -> bool:
80+
"""
81+
Removes a value from the collection. Returns true if the collection contained the specified element.
82+
"""
83+
if val not in self.m:
84+
return False
85+
idx_set = self.m[val]
86+
idx = list(idx_set)[0]
87+
last_idx = len(self.l) - 1
88+
self.l[idx] = self.l[last_idx]
89+
idx_set.remove(idx)
90+
91+
last_idx_set = self.m[self.l[last_idx]]
92+
if last_idx in last_idx_set:
93+
last_idx_set.remove(last_idx)
94+
if idx < last_idx:
95+
last_idx_set.add(idx)
96+
if not idx_set:
97+
self.m.pop(val)
98+
self.l.pop()
99+
return True
100+
101+
def getRandom(self) -> int:
102+
"""
103+
Get a random element from the collection.
104+
"""
105+
return -1 if len(self.l) == 0 else random.choice(self.l)
106+
107+
108+
109+
# Your RandomizedCollection object will be instantiated and called as such:
110+
# obj = RandomizedCollection()
111+
# param_1 = obj.insert(val)
112+
# param_2 = obj.remove(val)
113+
# param_3 = obj.getRandom()
56114
```
57115

58116
### **Java**
59117

60118
<!-- 这里可写当前语言的特殊实现逻辑 -->
61119

62120
```java
63-
121+
class RandomizedCollection {
122+
private Map<Integer, Set<Integer>> m;
123+
private List<Integer> l;
124+
private Random rnd;
125+
126+
/** Initialize your data structure here. */
127+
public RandomizedCollection() {
128+
m = new HashMap<>();
129+
l = new ArrayList<>();
130+
rnd = new Random();
131+
}
132+
133+
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
134+
public boolean insert(int val) {
135+
Set<Integer> idxSet = m.getOrDefault(val, new HashSet<>());
136+
idxSet.add(l.size());
137+
m.put(val, idxSet);
138+
l.add(val);
139+
return idxSet.size() == 1;
140+
}
141+
142+
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
143+
public boolean remove(int val) {
144+
if (!m.containsKey(val)) {
145+
return false;
146+
}
147+
Set<Integer> idxSet = m.get(val);
148+
int idx = idxSet.iterator().next();
149+
int lastIdx = l.size() - 1;
150+
l.set(idx, l.get(lastIdx));
151+
idxSet.remove(idx);
152+
153+
Set<Integer> lastIdxSet = m.get(l.get(lastIdx));
154+
lastIdxSet.remove(lastIdx);
155+
if (idx < lastIdx) {
156+
lastIdxSet.add(idx);
157+
}
158+
if (idxSet.isEmpty()) {
159+
m.remove(val);
160+
}
161+
l.remove(lastIdx);
162+
return true;
163+
}
164+
165+
/** Get a random element from the collection. */
166+
public int getRandom() {
167+
int size = l.size();
168+
return size == 0 ? -1 : l.get(rnd.nextInt(size));
169+
}
170+
}
171+
172+
/**
173+
* Your RandomizedCollection object will be instantiated and called as such:
174+
* RandomizedCollection obj = new RandomizedCollection();
175+
* boolean param_1 = obj.insert(val);
176+
* boolean param_2 = obj.remove(val);
177+
* int param_3 = obj.getRandom();
178+
*/
64179
```
65180

66181
### **...**

‎solution/0300-0399/0381.Insert Delete GetRandom O(1) - Duplicates allowed/README_EN.md‎

Lines changed: 112 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,13 +52,123 @@ randomizedCollection.getRandom(); // getRandom should return 1 and 2 both equall
5252
### **Python3**
5353

5454
```python
55-
55+
class RandomizedCollection:
56+
57+
def __init__(self):
58+
"""
59+
Initialize your data structure here.
60+
"""
61+
self.m = {}
62+
self.l = []
63+
64+
def insert(self, val: int) -> bool:
65+
"""
66+
Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
67+
"""
68+
idx_set = self.m.get(val, set())
69+
idx_set.add(len(self.l))
70+
self.m[val] = idx_set
71+
self.l.append(val)
72+
return len(idx_set) == 1
73+
74+
def remove(self, val: int) -> bool:
75+
"""
76+
Removes a value from the collection. Returns true if the collection contained the specified element.
77+
"""
78+
if val not in self.m:
79+
return False
80+
idx_set = self.m[val]
81+
idx = list(idx_set)[0]
82+
last_idx = len(self.l) - 1
83+
self.l[idx] = self.l[last_idx]
84+
idx_set.remove(idx)
85+
86+
last_idx_set = self.m[self.l[last_idx]]
87+
if last_idx in last_idx_set:
88+
last_idx_set.remove(last_idx)
89+
if idx < last_idx:
90+
last_idx_set.add(idx)
91+
if not idx_set:
92+
self.m.pop(val)
93+
self.l.pop()
94+
return True
95+
96+
def getRandom(self) -> int:
97+
"""
98+
Get a random element from the collection.
99+
"""
100+
return -1 if len(self.l) == 0 else random.choice(self.l)
101+
102+
103+
104+
# Your RandomizedCollection object will be instantiated and called as such:
105+
# obj = RandomizedCollection()
106+
# param_1 = obj.insert(val)
107+
# param_2 = obj.remove(val)
108+
# param_3 = obj.getRandom()
56109
```
57110

58111
### **Java**
59112

60113
```java
61-
114+
class RandomizedCollection {
115+
private Map<Integer, Set<Integer>> m;
116+
private List<Integer> l;
117+
private Random rnd;
118+
119+
/** Initialize your data structure here. */
120+
public RandomizedCollection() {
121+
m = new HashMap<>();
122+
l = new ArrayList<>();
123+
rnd = new Random();
124+
}
125+
126+
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
127+
public boolean insert(int val) {
128+
Set<Integer> idxSet = m.getOrDefault(val, new HashSet<>());
129+
idxSet.add(l.size());
130+
m.put(val, idxSet);
131+
l.add(val);
132+
return idxSet.size() == 1;
133+
}
134+
135+
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
136+
public boolean remove(int val) {
137+
if (!m.containsKey(val)) {
138+
return false;
139+
}
140+
Set<Integer> idxSet = m.get(val);
141+
int idx = idxSet.iterator().next();
142+
int lastIdx = l.size() - 1;
143+
l.set(idx, l.get(lastIdx));
144+
idxSet.remove(idx);
145+
146+
Set<Integer> lastIdxSet = m.get(l.get(lastIdx));
147+
lastIdxSet.remove(lastIdx);
148+
if (idx < lastIdx) {
149+
lastIdxSet.add(idx);
150+
}
151+
if (idxSet.isEmpty()) {
152+
m.remove(val);
153+
}
154+
l.remove(lastIdx);
155+
return true;
156+
}
157+
158+
/** Get a random element from the collection. */
159+
public int getRandom() {
160+
int size = l.size();
161+
return size == 0 ? -1 : l.get(rnd.nextInt(size));
162+
}
163+
}
164+
165+
/**
166+
* Your RandomizedCollection object will be instantiated and called as such:
167+
* RandomizedCollection obj = new RandomizedCollection();
168+
* boolean param_1 = obj.insert(val);
169+
* boolean param_2 = obj.remove(val);
170+
* int param_3 = obj.getRandom();
171+
*/
62172
```
63173

64174
### **...**

‎solution/0300-0399/0381.Insert Delete GetRandom O(1) - Duplicates allowed/Solution.java‎

Lines changed: 48 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,63 +1,52 @@
11
class RandomizedCollection {
2-
3-
private List<Integer> list;
4-
private Map<Integer, Set<Integer>> map;
5-
private Random random;
6-
7-
/** Initialize your data structure here. */
8-
public RandomizedCollection() {
9-
list = new ArrayList<>();
10-
map = new HashMap<>();
11-
random = new Random();
12-
}
13-
14-
/**
15-
* Inserts a value to the set. Returns true if the set did not already contain
16-
* the specified element.
17-
*/
18-
public boolean insert(int val) {
19-
boolean flag = false;
20-
if (!map.containsKey(val)) {
21-
flag = true;
22-
map.put(val, new HashSet<Integer>());
23-
}
24-
map.get(val).add(list.size());
25-
list.add(val);
26-
return flag;
27-
}
28-
29-
/**
30-
* Removes a value from the set. Returns true if the set contained the specified
31-
* element.
32-
*/
33-
public boolean remove(int val) {
34-
if (!map.containsKey(val)) {
35-
return false;
36-
}
37-
int removed = map.get(val).iterator().next();
38-
map.get(val).remove(removed);
39-
if (removed < list.size() - 1) {
40-
Integer tail = list.get(list.size() - 1);
41-
list.set(removed, tail);
42-
map.get(tail).remove(list.size() - 1);
43-
map.get(tail).add(removed);
44-
}
45-
list.remove(list.size() - 1);
46-
if (map.get(val).size() == 0) {
47-
map.remove(val);
48-
}
49-
return true;
50-
}
51-
52-
/** Get a random element from the set. */
53-
public int getRandom() {
54-
if (list.size() == 0) {
55-
return 0;
56-
}
57-
58-
return list.get(random.nextInt(list.size()));
59-
}
60-
2+
private Map<Integer, Set<Integer>> m;
3+
private List<Integer> l;
4+
private Random rnd;
5+
6+
/** Initialize your data structure here. */
7+
public RandomizedCollection() {
8+
m = new HashMap<>();
9+
l = new ArrayList<>();
10+
rnd = new Random();
11+
}
12+
13+
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
14+
public boolean insert(int val) {
15+
Set<Integer> idxSet = m.getOrDefault(val, new HashSet<>());
16+
idxSet.add(l.size());
17+
m.put(val, idxSet);
18+
l.add(val);
19+
return idxSet.size() == 1;
20+
}
21+
22+
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
23+
public boolean remove(int val) {
24+
if (!m.containsKey(val)) {
25+
return false;
26+
}
27+
Set<Integer> idxSet = m.get(val);
28+
int idx = idxSet.iterator().next();
29+
int lastIdx = l.size() - 1;
30+
l.set(idx, l.get(lastIdx));
31+
idxSet.remove(idx);
32+
33+
Set<Integer> lastIdxSet = m.get(l.get(lastIdx));
34+
lastIdxSet.remove(lastIdx);
35+
if (idx < lastIdx) {
36+
lastIdxSet.add(idx);
37+
}
38+
if (idxSet.isEmpty()) {
39+
m.remove(val);
40+
}
41+
l.remove(lastIdx);
42+
return true;
43+
}
44+
45+
/** Get a random element from the collection. */
46+
public int getRandom() {
47+
int size = l.size();
48+
return size == 0 ? -1 : l.get(rnd.nextInt(size));
49+
}
6150
}
6251

6352
/**

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /