leetCode-Record icon indicating copy to clipboard operation
leetCode-Record copied to clipboard

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

Open fireairforce opened this issue 5 years ago • 0 comments

这题开个队列和栈就可以了:

var MaxQueue = function() {
  this.queue = []
  this.maxQueue = []
}

/**
 * @return {number}
 */
MaxQueue.prototype.max_value = function() {
  return this.queue.length ? this.maxQueue[0] : -1
}

/**
 * @param {number} value
 * @return {void}
 */
MaxQueue.prototype.push_back = function(value) {
  this.queue.unshift(value)
  while (
    this.maxQueue.length &&
    value > this.maxQueue[this.maxQueue.length - 1]
  ) {
    this.maxQueue.pop()
  }
  this.maxQueue.push(value)
}

/**
 * @return {number}
 */
MaxQueue.prototype.pop_front = function() {
  if (this.queue.length === 0) {
    return -1
  }
  let val = this.queue.pop()
  if (this.maxQueue[0] === val) {
    this.maxQueue.shift()
  }
  return val
}


fireairforce avatar Mar 07 '20 06:03 fireairforce