双端队列
实际上就是一个每次push pop的常规queue和另一个首位是最大值的queue
type MaxQueue struct { Queue []int Max []int Size int } func Constructor() MaxQueue { return MaxQueue{ Queue: []int{}, Max: []int{}, Size: 0, } } func (this *MaxQueue) Max_value() int { if this.Size == 0 { return -1 } return this.Max[0] } func (this *MaxQueue) Push_back(value int) { this.Queue = append(this.Queue, value) if this.Size == 0 { this.Max = append(this.Max, value) } else { if value > this.Max[0] { this.Max = this.Max[0:0] this.Max = append(this.Max, value) this.Size++ return } for i := len(this.Max) - 1; this.Max[i] < value; i-- { this.Max = this.Max[:i] } this.Max = append(this.Max, value) } this.Size++ } func (this *MaxQueue) Pop_front() int { if this.Size == 0 { return -1 } num := this.Queue[0] if num == this.Max[0] { this.Max = this.Max[1:] } this.Queue = this.Queue[1:] this.Size-- return num }
end
原文地址:https://www.cnblogs.com/CherryTab/p/12436403.html
时间: 2024-09-28 11:06:33