JavaScript:leetcode_155. 最小棧(輔助棧)

題目說明

設計一個支持 push ,pop ,top 操作,並能在常數時間內檢索到最小元素的棧。

push(x) —— 將元素 x 推入棧中。
pop() —— 刪除棧頂的元素。
top() —— 獲取棧頂元素。
getMin() —— 檢索棧中的最小元素。
 

示例:

輸入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

輸出:
[null,null,null,null,-3,null,0,-2]

解釋:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.
 

提示:

pop、top 和 getMin 操作總是在 非空棧 上調用。

解題思路一

  1. 首先確定棧的特點吧,先進後出,只能從棧頂進棧出棧,然後我們用數組來模擬他,將數組末尾當作棧頂,在此進棧出棧。
  2. 其實就是實現一個數組的push,pop功能,然後增加獲取最小值的api和返回數組最後一位的api
  3. 由於最開始棧爲空,所以棧是通過push,或者pop得到的。並且題目要求最小值要通過常數次操作得到,也就getMin的時間複雜度爲O(1).那我們可以在push,pop的過程中,確定最小值。

代碼實現一

/**
 * initialize your data structure here.
 */
var MinStack = function() {
    return void (
            this.stack = [],
            this.min = [Number.MAX_SAFE_INTEGER], //整數類型的最大值
            this.topValue = null
        );
};

/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
    return void (this.stack[this.stack.length] = x, this.topValue = x, this.min[this.min.length] = (x > this.min[this.min.length - 1] ? this.min[this.min.length - 1] : x));
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
    return void (this.stack.length -= 1, this.topValue = this.stack[this.stack.length - 1], this.min.length -= 1);
};

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

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

/**
 * 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()
 */
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章