难度:中等

    题目描述:
    请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。

    若队列为空,pop_front 和 max_value 需要返回 -1

    示例:

    1. 输入:
    2. ["MaxQueue","push_back","push_back","max_value","pop_front","max_value"]
    3. [[],[1],[2],[],[],[]]
    4. 输出: [null,null,null,2,1,2]

    解题思路:

    1. var MaxQueue = function() {
    2. this.queue1 = [];
    3. this.queue2 = [];
    4. };
    5. /**
    6. * @return {number}
    7. */
    8. MaxQueue.prototype.max_value = function() {
    9. if (this.queue2.length) {
    10. return this.queue2[0];
    11. }
    12. return -1;
    13. };
    14. /**
    15. * @param {number} value
    16. * @return {void}
    17. */
    18. MaxQueue.prototype.push_back = function(value) {
    19. this.queue1.push(value);
    20. while (this.queue2.length && this.queue2[this.queue2.length - 1] < value) {
    21. this.queue2.pop();
    22. }
    23. this.queue2.push(value);
    24. };
    25. /**
    26. * @return {number}
    27. */
    28. MaxQueue.prototype.pop_front = function() {
    29. if (!this.queue1.length) {
    30. return -1;
    31. }
    32. const value = this.queue1.shift();
    33. if (value === this.queue2[0]) {
    34. this.queue2.shift();
    35. }
    36. return value;
    37. };