Skip to content

Commit 18bbabc

Browse files
aQuaaQua
aQua
authored and
aQua
committed
380 adding
1 parent d0ef718 commit 18bbabc

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# [380. Insert Delete GetRandom O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/)
2+
3+
## 题目
4+
Design a data structure that supports all following operations in average O(1) time.
5+
6+
1. `insert(val)`: Inserts an item val to the set if not already present.
7+
1. `remove(val)`: Removes an item val from the set if present.
8+
1. `getRandom`: Returns a random element from current set of elements. Each element must have the `same probability` of being returned.
9+
10+
11+
12+
Example:
13+
```
14+
// Init an empty set.
15+
RandomizedSet randomSet = new RandomizedSet();
16+
17+
// Inserts 1 to the set. Returns true as 1 was inserted successfully.
18+
randomSet.insert(1);
19+
20+
// Returns false as 2 does not exist in the set.
21+
randomSet.remove(2);
22+
23+
// Inserts 2 to the set, returns true. Set now contains [1,2].
24+
randomSet.insert(2);
25+
26+
// getRandom should return either 1 or 2 randomly.
27+
randomSet.getRandom();
28+
29+
// Removes 1 from the set, returns true. Set now contains [2].
30+
randomSet.remove(1);
31+
32+
// 2 was already in the set, so return false.
33+
randomSet.insert(2);
34+
35+
// Since 2 is the only number in the set, getRandom always return 2.
36+
randomSet.getRandom();
37+
```
38+
39+
## 解题思路
40+
41+
见程序注释
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package Problem0380
2+
3+
type RandomizedSet struct {
4+
}
5+
6+
/** Initialize your data structure here. */
7+
func Constructor() RandomizedSet {
8+
9+
}
10+
11+
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
12+
func (this *RandomizedSet) Insert(val int) bool {
13+
14+
}
15+
16+
/** Removes a value from the set. Returns true if the set contained the specified element. */
17+
func (this *RandomizedSet) Remove(val int) bool {
18+
19+
}
20+
21+
/** Get a random element from the set. */
22+
func (this *RandomizedSet) GetRandom() int {
23+
24+
}
25+
26+
/**
27+
* Your RandomizedSet object will be instantiated and called as such:
28+
* obj := Constructor();
29+
* param_1 := obj.Insert(val);
30+
* param_2 := obj.Remove(val);
31+
* param_3 := obj.GetRandom();
32+
*/
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package Problem0380
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func Test_Problem0380(t *testing.T) {
10+
ast := assert.New(t)
11+
12+
}

0 commit comments

Comments
 (0)