352.data-stream-as-disjoint-intervals.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * Definition for an inval.
  3. * type Interval struct {
  4. * Start int
  5. * End int
  6. * }
  7. */
  8. type SummaryRanges struct {
  9. is []Interval
  10. }
  11. /** Initialize your data structure here. */
  12. func Constructor() SummaryRanges {
  13. return SummaryRanges{}
  14. }
  15. func (this *SummaryRanges) AddNum(val int) {
  16. n := len(this.is)
  17. if n == 0 {
  18. this.is = []Interval{{val, val}}
  19. return
  20. }
  21. beg, end := 0, n-1
  22. for beg <= end {
  23. mid := beg + (end-beg)/2
  24. if in := this.is[mid]; in.Start <= val && val <= in.End {
  25. return
  26. } else if val < in.Start {
  27. end = mid - 1
  28. } else if in.End < val {
  29. beg = mid + 1
  30. }
  31. }
  32. if beg == n {
  33. if val == this.is[n-1].End+1 {
  34. this.is[n-1].End++
  35. } else {
  36. this.is = append(this.is, Interval{val, val})
  37. }
  38. } else if beg == 0 {
  39. if val == this.is[0].Start-1 {
  40. this.is[0].Start--
  41. } else {
  42. nis := make([]Interval, n+1)
  43. nis[0] = Interval{val, val}
  44. copy(nis[1:], this.is)
  45. this.is = nis
  46. }
  47. } else {
  48. if l, r := val == this.is[beg-1].End+1, val == this.is[beg].Start-1; l && r {
  49. this.is[beg].Start = this.is[beg-1].Start
  50. copy(this.is[beg-1:], this.is[beg:])
  51. this.is = this.is[:n-1]
  52. } else if l {
  53. this.is[beg-1].End++
  54. } else if r {
  55. this.is[beg].Start--
  56. } else {
  57. nis := make([]Interval, n+1)
  58. copy(nis, this.is[:beg])
  59. nis[beg] = Interval{val, val}
  60. copy(nis[beg+1:], this.is[beg:])
  61. this.is = nis // Since append([]T, []T...) is rather inefficient, copy is the best choice
  62. }
  63. }
  64. }
  65. func (this *SummaryRanges) GetIntervals() []Interval {
  66. return this.is
  67. }
  68. /**
  69. * Your SummaryRanges object will be instantiated and called as such:
  70. * obj := Constructor();
  71. * obj.AddNum(val);
  72. * param_2 := obj.GetIntervals();
  73. */