面试题59 - II. 队列的最大值 Golang 双数组

面试题59 - II. 队列的最大值

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

思路

我看到这个题目的时候最开始想到的是维护两个数组,一个存值,一个存大小排行。但维护排行数组非常麻烦,每次pop/push都可能需要更新很多元素。
这里参考了官方解题的思路,也是双数组。
考虑一个递增的数组,我们只需要存储最后一个值,前面的值都不会影响最大值。
考虑一个递减的数组,每一个值都需要存储,每pop一个值,后一个值就是新的最大值。

我的解答

在这里插入图片描述

type MaxQueue struct {
	AscDeque []int
	queue []int
}


func Constructor() MaxQueue {
	return MaxQueue{
		AscDeque: []int{},
		queue:    []int{},
	}
}


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


func (this *MaxQueue) Push_back(value int)  {

	for len(this.AscDeque)>0&&this.AscDeque[len(this.AscDeque)-1]<value{
		this.AscDeque=this.AscDeque[:len(this.AscDeque)-1]
	}
	this.AscDeque=append(this.AscDeque,value)
	this.queue=append(this.queue,value)
}


func (this *MaxQueue) Pop_front() int {
	if len(this.AscDeque)==0{
		return -1
	}
	if this.queue[0]==this.AscDeque[0]{
		this.AscDeque=this.AscDeque[1:]
	}
	tmp:=this.queue[0]
	this.queue=this.queue[1:]
	return tmp
}
发布了38 篇原创文章 · 获赞 0 · 访问量 1036

猜你喜欢

转载自blog.csdn.net/Cyan1956/article/details/104710260
今日推荐