155.最小棧

#155.最小棧
2019-11-30 19:32:58 +0800
categories: LeetCode

設計一個支持 push,pop,top 操作,並能在常數時間內檢索到最小元素的棧。
push(x) – 將元素 x 推入棧中。
pop() – 刪除棧頂的元素。
top() – 獲取棧頂元素。
getMin() – 檢索棧中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/min-stack
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。


信息

  • 支持push、pop、top、getMin等操作
  • getMin()爲常數時間複雜度
  • 支持new

思路

  • 函數原型或者類,this.arr=new Array(),所有操作基於this.arr
  • getMin()可以用遍歷比較的方法

解答

/**
 * initialize your data structure here.
 */
var MinStack = function() {
    this.array=[...arguments];
};

/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
    this.array[this.array.length]=x;
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
    this.array.pop();
};

/**
 * @return {number}
 */
MinStack.prototype.top = function() {
    return this.array[this.array.length-1];
};

/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
    var min=Number.MAX_VALUE;
    for(let elem of this.array){
        if(elem<min){
            min=elem;
        }
    }
    return min;
};

/** 
 * Your MinStack object will be instantiated and called as such:
 * var obj = new MinStack()
 * obj.push(x)
 * obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.getMin()
 */

但是上面的運行成績慘不忍睹,有沒有優化方法?顯然是有的,顯然這道題中複雜度最高的就是getMin(),其餘不過是一步操作而已,剛開始我故步自封於如何快速查找最小值,而忽略了它初始狀態是一個空棧,後面每一次操作都會更新最小值,而不需要到了求getMIN()財去查找
所以更新爲:

var MinStack = function() {
  this.stack = [];
  this.min = Number.MAX_VALUE;
};

/**
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
  // update 'min'
  const min = this.min;
  if (x < this.min) {
    this.min = x;
  }
  return this.stack.push(x - min);
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
  const item = this.stack.pop();
  const min = this.min;

  if (item < 0) {
    this.min = min - item;
    return min;
  }
  return item + min;
};

/**
 * @return {number}
 */
MinStack.prototype.top = function() {
  const item = this.stack[this.stack.length - 1];
  const min = this.min;

  if (item < 0) {
    return min;
  }
  return item + min;
};

/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
  return this.min;
};

/**
 * Your MinStack object will be instantiated and called as such:
 * var obj = new MinStack()
 * obj.push(x)
 * obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.getMin()
 */

leetCode分類刷題   該地址長期、每週更新LeetCode分類刷題

參考資料
  leetcode題解

發佈了23 篇原創文章 · 獲贊 4 · 訪問量 797
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章