380.insert-delete-getrandom-o1.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. var empty struct{} = struct{}{}
  2. type RandomizedSet struct {
  3. set map[int]struct{}
  4. key []int
  5. }
  6. /** Initialize your data structure here. */
  7. func Constructor() RandomizedSet {
  8. return RandomizedSet{
  9. set: make(map[int]struct{}),
  10. }
  11. }
  12. /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
  13. func (this *RandomizedSet) Insert(val int) bool {
  14. if _, ok := this.set[val]; ok {
  15. return false
  16. }
  17. this.set[val] = empty
  18. this.key = append(this.key, val)
  19. return true
  20. }
  21. /** Removes a value from the set. Returns true if the set contained the specified element. */
  22. func (this *RandomizedSet) Remove(val int) bool {
  23. if _, ok := this.set[val]; ok {
  24. delete(this.set, val)
  25. if n := len(this.set); 2*n < len(this.key) {
  26. this.key = make([]int, n)
  27. i := 0
  28. for k := range this.set {
  29. this.key[i] = k
  30. i++
  31. }
  32. }
  33. return true
  34. }
  35. return false
  36. }
  37. /** Get a random element from the set. */
  38. func (this *RandomizedSet) GetRandom() int {
  39. for {
  40. val := this.key[rand.Intn(len(this.key))]
  41. if _, ok := this.set[val]; ok {
  42. return val
  43. }
  44. }
  45. }
  46. /**
  47. * Your RandomizedSet object will be instantiated and called as such:
  48. * obj := Constructor();
  49. * param_1 := obj.Insert(val);
  50. * param_2 := obj.Remove(val);
  51. * param_3 := obj.GetRandom();
  52. */