restructure solutions dir
This commit is contained in:
parent
f9ddad5f88
commit
ccb8b5673b
10 changed files with 0 additions and 0 deletions
69
solutions/3/q380/solution.go
Normal file
69
solutions/3/q380/solution.go
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
package q380
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"runtime/debug"
|
||||
)
|
||||
|
||||
func init() {
|
||||
debug.SetMemoryLimit(16 << 20)
|
||||
}
|
||||
|
||||
var rng *rand.Rand = rand.New(rand.NewSource(42))
|
||||
|
||||
type RandomizedSet struct {
|
||||
vals []int
|
||||
idx map[int]int // the index of the element in vals
|
||||
}
|
||||
|
||||
func Constructor() RandomizedSet {
|
||||
return RandomizedSet{
|
||||
vals: []int{},
|
||||
idx: map[int]int{},
|
||||
}
|
||||
}
|
||||
|
||||
// Insert Inserts an item val into the set if not present. Returns true if the
|
||||
// item was not present, false otherwise.
|
||||
func (rs *RandomizedSet) Insert(val int) bool {
|
||||
if _, present := rs.idx[val]; present {
|
||||
return false
|
||||
}
|
||||
rs.idx[val] = len(rs.vals)
|
||||
rs.vals = append(rs.vals, val)
|
||||
return true
|
||||
}
|
||||
|
||||
// Remove Removes an item val from the set if present. Returns true if the item
|
||||
// was present, false otherwise.
|
||||
func (rs *RandomizedSet) Remove(val int) bool {
|
||||
idx, present := rs.idx[val]
|
||||
if !present {
|
||||
return false
|
||||
}
|
||||
delete(rs.idx, val)
|
||||
|
||||
idxLast := len(rs.vals) - 1
|
||||
if idx != idxLast {
|
||||
rs.vals[idx] = rs.vals[idxLast]
|
||||
rs.idx[rs.vals[idx]] = idx
|
||||
}
|
||||
rs.vals = rs.vals[:idxLast]
|
||||
return true
|
||||
}
|
||||
|
||||
// GetRandom Returns a random element from the current set of elements (it's
|
||||
// guaranteed that at least one element exists when this method is called).
|
||||
// Each element must have the same probability of being returned.
|
||||
func (rs *RandomizedSet) GetRandom() int {
|
||||
i := rng.Intn(len(rs.vals))
|
||||
return rs.vals[i]
|
||||
}
|
||||
|
||||
/**
|
||||
* Your RandomizedSet object will be instantiated and called as such:
|
||||
* obj := Constructor();
|
||||
* param_1 := obj.Insert(val);
|
||||
* param_2 := obj.Remove(val);
|
||||
* param_3 := obj.GetRandom();
|
||||
*/
|
||||
Loading…
Add table
Add a link
Reference in a new issue