😕题目描述

https://leetcode-cn.com/problems/insert-delete-getrandom-o1/

😔分析

map+slice

😏答案

  1. import "math/rand"
  2. type RandomizedSet struct {
  3. mp map[int]int
  4. sli []int
  5. length int
  6. }
  7. func Constructor() RandomizedSet {
  8. return RandomizedSet{
  9. mp: make(map[int]int),
  10. sli: make([]int, 0),
  11. length: 0,
  12. }
  13. }
  14. func (this *RandomizedSet) Insert(val int) bool {
  15. if _, ok := this.mp[val]; ok {
  16. return false
  17. }
  18. if len(this.sli) == this.length {
  19. this.sli = append(this.sli, val)
  20. } else {
  21. this.sli[this.length] = val
  22. }
  23. this.mp[val] = this.length
  24. this.length++
  25. return true
  26. }
  27. func (this *RandomizedSet) Remove(val int) bool {
  28. if _, ok := this.mp[val]; !ok {
  29. return false
  30. }
  31. end := this.sli[this.length - 1]
  32. this.sli[this.length - 1], this.sli[this.mp[val]] = this.sli[this.mp[val]], this.sli[this.length - 1]
  33. this.mp[end], this.mp[val] = this.mp[val], this.mp[end]
  34. this.length--
  35. delete(this.mp, val)
  36. return true
  37. }
  38. func (this *RandomizedSet) GetRandom() int {
  39. index := rand.Int() % this.length
  40. return this.sli[index]
  41. }