Skip to content

Commit 924d279

Browse files
aQuaaQua
aQua
authored and
aQua
committed
380 accepted
1 parent 18bbabc commit 924d279

File tree

2 files changed

+63
-5
lines changed

2 files changed

+63
-5
lines changed

Algorithms/0380.insert-delete-getrandom-o1/insert-delete-getrandom-o1.go

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,59 @@
11
package Problem0380
22

3+
import "math/rand"
4+
5+
// RandomizedSet 是一个随机获取的集合
36
type RandomizedSet struct {
7+
rec map[int]bool
48
}
59

10+
// Constructor returns RandomizedSet
611
/** Initialize your data structure here. */
712
func Constructor() RandomizedSet {
8-
13+
return RandomizedSet{
14+
rec: make(map[int]bool),
15+
}
916
}
1017

18+
// Insert 插入数据
1119
/** 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-
20+
func (r *RandomizedSet) Insert(val int) bool {
21+
if _, ok := r.rec[val]; ok {
22+
return false
23+
}
24+
r.rec[val] = true
25+
return true
1426
}
1527

28+
// Remove 删除数据
1629
/** Removes a value from the set. Returns true if the set contained the specified element. */
17-
func (this *RandomizedSet) Remove(val int) bool {
30+
func (r *RandomizedSet) Remove(val int) bool {
31+
if _, ok := r.rec[val]; ok {
32+
delete(r.rec, val)
33+
return true
34+
}
1835

36+
return false
1937
}
2038

39+
// GetRandom 获取随机数据
2140
/** Get a random element from the set. */
22-
func (this *RandomizedSet) GetRandom() int {
41+
func (r *RandomizedSet) GetRandom() int {
42+
if len(r.rec) == 0 {
43+
return 0
44+
}
45+
46+
rnd := rand.Int() % len(r.rec)
47+
res := 0
48+
for k := range r.rec {
49+
if rnd == 0 {
50+
res = k
51+
break
52+
}
53+
rnd--
54+
}
2355

56+
return res
2457
}
2558

2659
/**

Algorithms/0380.insert-delete-getrandom-o1/insert-delete-getrandom-o1_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,29 @@ import (
99
func Test_Problem0380(t *testing.T) {
1010
ast := assert.New(t)
1111

12+
rs := Constructor()
13+
14+
ast.Equal(0, rs.GetRandom(), "从空集合中,只能取出0")
15+
16+
ast.True(rs.Insert(1), "插入1")
17+
18+
ast.False(rs.Remove(2), "删除2")
19+
20+
ast.True(rs.Insert(2), "插入2")
21+
22+
ast.Contains([]int{1, 2}, rs.GetRandom(), "返回1或2")
23+
24+
ast.True(rs.Remove(1), "删除1")
25+
26+
ast.False(rs.Insert(2), "再一次插入2")
27+
28+
ast.Equal(2, rs.GetRandom(), "从只有2的集合中随机取出2")
29+
30+
length := 100
31+
result := make([]int, length)
32+
for i := 0; i < 100; i++ {
33+
rs.Insert(i)
34+
result[i] = i
35+
}
36+
ast.Contains(result, rs.GetRandom(), "随机获取0~100之间的数")
1237
}

0 commit comments

Comments
 (0)