前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >golang刷leetcode 技巧(15)队列的最大值

golang刷leetcode 技巧(15)队列的最大值

作者头像
golangLeetcode
发布2022-08-02 18:40:41
1410
发布2022-08-02 18:40:41
举报
文章被收录于专栏:golang算法架构leetcode技术php

请定义一个队列并实现函数 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]

示例 2:

输入:

["MaxQueue","pop_front","max_value"]

[[],[],[]]

输出: [null,-1,-1]

限制:

1 <= push_back,pop_front,max_value的总操作数 <= 10000

1 <= value <= 10^5

解题思路:

1,对于先进先出,O(1),显然是一个基本的队列可以搞定

2,但是实现O(1)的max,需要优先队列

3,但是本题的技巧在于:优先队列只需要按照插入顺序,保留前几个

4,具体原因:

A,如果插入元素比现在优先队列元素都小,插入队尾即可,这很好理解

B,如果插入元素A比现在优先队列某些元素a,b,c大,那么,a,b,c 出队的时候,最大元素肯定大于等于A,所以,没有必要维护a,b,c的优先队列了

代码实现

代码语言:javascript
复制
type MaxQueue struct {
    queue []int
    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)  {
    this.queue=append(this.queue,value)
    i:=0
    for ;i<len(this.max);i++{
        if this.max[i]<=value{
            break
        }
    }
    this.max=append(this.max[:i],value)
}


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


/**
 * 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();
 */
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-02-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 golang算法架构leetcode技术php 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档