您的位置:首页 > 职场人生

leetcode每日一题——面试题59 - II. 队列的最大值

2020-03-09 23:51 696 查看

请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
示例 1:
输入:
[“MaxQueue”,“push_back”,“push_back”,“max_value”,“pop_front”,“max_value”]
[[],[1],[2],[],[],[]]
输出: [null,null,null,2,1,2]
解题思路:首先需要认真读懂题目,理解每个函数的意思,这里我们用一个双端队列,保证是单调递减的队列,每次返回最大值就是双端队列的首部元素。正常队列进行正常的出队与入队,在出队之前与双端队列头元素进行比较,当正常队列进行pop操作时,如果正常队列首部的值等于双端队列首部的值,那么双端队列同样需要进行pop操作。
双端队列知识自行百度了解。

class MaxQueue {

Queue<Integer> queue = null;//正常队列
Deque<Integer> maxqueue = null;//结果队列 维护一个单调递减的双端队列
public MaxQueue() {
queue = new LinkedList<>();
maxqueue = new LinkedList<>();
}

public int max_value() {
if(maxqueue.isEmpty()){
return -1;
}
return maxqueue.peek();//当前最大值 返回出队列的头元素
}

public void push_back(int value) {
queue.offer(value);
while(!maxqueue.isEmpty() && value > maxqueue.getLast()){//维护单调递减
maxqueue.pollLast();
}
maxqueue.offer(value);
}

public int pop_front() {
if(queue.isEmpty()){
return -1;
}
int temp = queue.poll();//队列的出队操作
if(temp == maxqueue.peek()){
maxqueue.poll();
}
return temp;
}
}
// 5 4 3 6
// 6
/**
* Your MaxQueue object will be instantiated and called as such:
* MaxQueue obj = new MaxQueue();
* int param_1 = obj.max_value();
* obj.push_back(value);
* int param_3 = obj.pop_front();
*/
  • 点赞
  • 收藏
  • 分享
  • 文章举报
小鱼儿@ 发布了5 篇原创文章 · 获赞 0 · 访问量 64 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: