Golang maximum queue dual array II - 59 interview questions.

59 interview questions - II maximum queue.

Define and implement a queue maximum queue function max_value obtained, requiring max_value function, and time complexity push_back pop_front are O (1).

If the queue is empty, pop_front max_value and need -1

Example 1:

Input:
[ "MaxQueue", "push_back", "push_back", "MAX_VALUE", "pop_front", "MAX_VALUE"]
[[], [. 1], [2], [], [], []]
Output: [null, null, null, 2,1,2 ]

Example 2:

Input:
[ "MaxQueue", "pop_front", "MAX_VALUE"]
[[], [], []]
Output: [null, -1, -1]

limit:

1 <Total operating = push_back, pop_front, max_value of <= 10000
1 <= value <= 10 ^. 5

Thinking

I saw this when the subject began to think of most is to maintain two arrays, a stored value, a memory size ranking. But maintenance is very troublesome ranking arrays, each pop / push may need to be updated many elements.
Here reference to the official problem-solving ideas, but also double array.
Consider an increasing array, we only need to store the last value, it will not affect the value of the previous maximum.
Consider an array of diminishing, each value will need to be stored, every pop a value, that is, after a new maximum value.

My answer

Here Insert Picture Description

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
}
Published 38 original articles · won praise 0 · Views 1036

Guess you like

Origin blog.csdn.net/Cyan1956/article/details/104710260