Skip to content

Commit 97089f4

Browse files
committed
Create 面试题59 - II. 队列的最大值.js
1 parent fdc3aa6 commit 97089f4

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
var MaxQueue = function() {
2+
this.queue = [];
3+
this.max = [];
4+
};
5+
6+
/**
7+
* @return {number}
8+
*/
9+
MaxQueue.prototype.max_value = function() {
10+
if (this.max.length) {
11+
return this.max[0];
12+
} else {
13+
return -1;
14+
}
15+
};
16+
17+
/**
18+
* @param {number} value
19+
* @return {void}
20+
*/
21+
MaxQueue.prototype.push_back = function(value) {
22+
this.queue.push(value);
23+
while (this.max.length >= 0 && this.max[this.max.length - 1] < value) {
24+
this.max.pop();
25+
}
26+
this.max.push(value);
27+
};
28+
29+
/**
30+
* @return {number}
31+
*/
32+
MaxQueue.prototype.pop_front = function() {
33+
if (this.queue.length === 0) {
34+
return -1;
35+
}
36+
const value = this.queue.shift();
37+
if (value === this.max[0]) {
38+
this.max.shift();
39+
}
40+
return value;
41+
};
42+
43+
/**
44+
* Your MaxQueue object will be instantiated and called as such:
45+
* var obj = new MaxQueue()
46+
* var param_1 = obj.max_value()
47+
* obj.push_back(value)
48+
* var param_3 = obj.pop_front()
49+
*/

0 commit comments

Comments
 (0)