Featured image of post 剑指 Offer 59 - II. 队列的最大值

剑指 Offer 59 - II. 队列的最大值

题目描述

请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数 max_valuepush_backpop_front均摊时间复杂度都是 O (1)。

若队列为空,pop_frontmax_value 需要返回 -1

示例 1:

  • 输入: [“MaxQueue”,“push_back”,“push_back”,“max_value”,“pop_front”,“max_value”] [[],[1],[2],[],[],[]]
  • 输出: [null,null,null,2,1,2]

示例 2:

  • 输入: [“MaxQueue”,“pop_front”,“max_value”] [[],[],[]]
  • 输出: [null,-1,-1]

限制:

  • 1 <= push_back,pop_front,max_value的总操作数 <= 10000
  • 1 <= value <= 10^5

解法一:维护一个单调队列

本算法基于问题的一个重要性质:当一个元素进入队列的时候,它前面所有比它小的元素就不会再对答案产生影响。

维护一个单调队列 max,满足从队头到队尾的元素单调递减。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
type MaxQueue struct {
    queue []int
    // 对于任意 0 <= i < j < len(max),有 max[i] >= max[j]
    max   []int
}

func Constructor() MaxQueue {
    return MaxQueue{}
}

func (this *MaxQueue) Max_value() int {
    if len(this.max) == 0 {
        return -1
    }
    return this.max[0]
}

func (this *MaxQueue) Push_back(value int) {
    max, queue := this.max, this.queue
    queue = append(queue, value)
    for len(max) > 0 && max[len(max)-1] < value {
        max = max[:len(max)-1]
    }
    max = append(max, value)
    this.queue = queue
    this.max = max
}

func (this *MaxQueue) Pop_front() int {
    max, queue := this.max, this.queue
    if len(queue) == 0 {
        return -1
    }
    val := queue[0]
    if max[0] == val {
        this.max = max[1:]
    }
    this.queue = queue[1:]
    return val
}

/**
 * Your MaxQueue object will be instantiated and called as such:
 * obj := Constructor();
 * param_1 := obj.Max_value();
 * obj.Push_back(value);
 * param_3 := obj.Pop_front();
 */
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/06/15 19:23:39
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计