From a619f87b0cc221d10da783d4631249fca4f96c84 Mon Sep 17 00:00:00 2001 From: Josue Kouka Date: Tue, 10 Jan 2023 11:57:33 -0800 Subject: [PATCH] Create 0380-insert-delete-getrandom.go --- go/0380-insert-delete-getrandom.go | 43 ++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 go/0380-insert-delete-getrandom.go diff --git a/go/0380-insert-delete-getrandom.go b/go/0380-insert-delete-getrandom.go new file mode 100644 index 000000000..7d28c52bc --- /dev/null +++ b/go/0380-insert-delete-getrandom.go @@ -0,0 +1,43 @@ +import "math/rand" + +type RandomizedSet struct { + hash map[int]int + array []int + length int +} + +func Constructor() RandomizedSet { + return RandomizedSet{ + hash: make(map[int]int), + array: []int{}, + length: 0, + } +} + +func (this *RandomizedSet) Insert(val int) bool { + if _, ok := this.hash[val]; ok { + return false + } + this.array = append(this.array, val) + this.hash[val] = len(this.array) - 1 + this.length++ + return true +} + +func (this *RandomizedSet) Remove(val int) bool { + idx, ok := this.hash[val] + if !ok { + return false + } + last := this.array[this.length-1] + this.array[idx] = last + this.hash[last] = idx + this.array = this.array[:len(this.array)-1] + delete(this.hash, val) + this.length-- + return true +} + +func (this *RandomizedSet) GetRandom() int { + return this.array[rand.Intn(this.length)] +} pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy