432.all-oone-data-structure.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. type none struct{}
  2. type pair {
  3. key int
  4. set map[string]none
  5. }
  6. type AllOne struct {
  7. m map[string]*list.Element
  8. li *list.List
  9. }
  10. /** Initialize your data structure here. */
  11. func Constructor() AllOne {
  12. return AllOne{
  13. m: make(map[string]*list.Element),
  14. li: list.New(),
  15. }
  16. }
  17. /** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
  18. func (this *AllOne) Inc(key string) {
  19. if val, ok := this.m[key]; ok { // Increments
  20. next := val.Next()
  21. if next == nil || val.(pair).key+1 != next.(pair).key { // Insert after
  22. next =
  23. } else { // Increment after
  24. }
  25. this.m[key] = next
  26. } else { // Inserts
  27. if this.li.Len() == 0 || this.li.Front().Value.(pair).key != 1 {
  28. this.li.PushFront(pair{1, map[string]none{key: none{}})
  29. } else {
  30. this.li.Front().Value.(pair).set[key] = none{}
  31. }
  32. this.m[key] = this.li.Front()
  33. }
  34. }
  35. /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
  36. func (this *AllOne) Dec(key string) {
  37. if val, ok := this.m[key]; ok {
  38. }
  39. }
  40. /** Returns one of the keys with maximal value. */
  41. func (this *AllOne) GetMaxKey() string {
  42. if this.li.Len() == 0 {
  43. return ""
  44. }
  45. set := this.li.Back().Value.(pair).set
  46. for k := range set {
  47. return k
  48. }
  49. }
  50. /** Returns one of the keys with Minimal value. */
  51. func (this *AllOne) GetMinKey() string {
  52. if this.li.Len() == 0 {
  53. return ""
  54. }
  55. set := this.li.Front().Value.(pair).set
  56. for k := range set {
  57. return k
  58. }
  59. }
  60. /**
  61. * Your AllOne object will be instantiated and called as such:
  62. * obj := Constructor();
  63. * obj.Inc(key);
  64. * obj.Dec(key);
  65. * param_3 := obj.GetMaxKey();
  66. * param_4 := obj.GetMinKey();
  67. */