Skip to content

Commit

Permalink
feat: 381.Insert Delete GetRandom O(1) Duplicates allowed
Browse files Browse the repository at this point in the history
  • Loading branch information
kimi0230 committed Feb 7, 2024
1 parent fafe00a commit 7c9e27d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package insertdeletegetrandomo1duplicatesallowed

import "math/rand"
import (
"math/rand"
)

// 時間複雜 O(1), 空間複雜 O(n)
type RandomizedCollection struct {
Expand Down Expand Up @@ -43,13 +45,15 @@ func (this *RandomizedCollection) Remove(val int) bool {
break
}

// 與最後一筆交換
// 將最後一筆移到要替換的id
this.arr[i] = this.arr[this.size-1]
delete(ids, i)
// 因為把最後一個元素移到前面了
delete(this.set[this.arr[i]], this.size-1)

if i < this.size-1 {
// fmt.Printf("i =%d, this.size =%d\t", i, this.size)
// 將最後一個元素的index的map中, 最後一個元素的index改為i
this.set[this.arr[i]][i] = struct{}{}
}
if len(ids) == 0 {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package insertdeletegetrandomo1duplicatesallowed

import (
"fmt"
"reflect"
"testing"
)
Expand All @@ -21,6 +22,17 @@ var tests = []struct {
nil, true, false, true, true, 1,
},
},
// {
// []string{
// "RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom",
// },
// []int{
// 0, 1, 1, 2, 0, 1, 0,
// },
// []interface{}{
// nil, true, false, true, 2, true, false, 2,
// },
// },
}

func TestInsertdeletegetrandom(t *testing.T) {
Expand All @@ -39,6 +51,7 @@ func TestInsertdeletegetrandom(t *testing.T) {
case "getRandom":
result = append(result, rSet.GetRandom())
}
fmt.Println(rSet.set)
}
if !reflect.DeepEqual(result, tt.want) {
t.Errorf("got = %v, want = %v", result, tt.want)
Expand Down

0 comments on commit 7c9e27d

Please sign in to comment.