381.insert-delete-getrandom-o1-duplicates-allowed.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. type pair struct {
  2. _1 int
  3. _2 *list.Element
  4. }
  5. type RandomizedCollection struct {
  6. nums []pair
  7. size int
  8. pos map[int]*list.List // Hash map + linked list, O(1) get random, O(1) insert, O(1) remove (average)
  9. }
  10. /** Initialize your data structure here. */
  11. func Constructor() RandomizedCollection {
  12. return RandomizedCollection{pos: make(map[int]*list.List)}
  13. }
  14. /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
  15. func (this *RandomizedCollection) Insert(val int) bool {
  16. li, ok := this.pos[val]
  17. if !ok {
  18. li = list.New()
  19. this.pos[val] = li
  20. }
  21. ele := li.PushBack(this.size)
  22. this.nums = append(this.nums, pair{val, ele})
  23. this.size++
  24. return !ok
  25. }
  26. /** Removes a value from the collection. Returns true if the collection contained the specified element. */
  27. func (this *RandomizedCollection) Remove(val int) bool {
  28. li, ok := this.pos[val]
  29. if !ok {
  30. return false
  31. }
  32. idx := li.Remove(li.Front()).(int)
  33. this.size--
  34. this.nums[idx] = this.nums[this.size]
  35. this.nums[idx]._2.Value = idx
  36. this.nums = this.nums[:this.size]
  37. if li.Len() == 0 {
  38. delete(this.pos, val)
  39. }
  40. return true
  41. }
  42. /** Get a random element from the collection. */
  43. func (this *RandomizedCollection) GetRandom() int {
  44. return this.nums[rand.Intn(this.size)]._1
  45. }
  46. /**
  47. * Your RandomizedCollection 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. */