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(); */