1. 程式人生 > 其它 >最小棧 -棧 leetcode題庫第一百五十五題

最小棧 -棧 leetcode題庫第一百五十五題

技術標籤:資料結構leetcode資料結構

來自力扣leetcode題庫裡面的第155題,《最小棧》

連結:https://leetcode-cn.com/problems/min-stack
題目為:

設計一個支援 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.

先說一下思路

我用的是資料棧+輔助棧的形式做的,資料棧用來儲存所有的資料,輔助棧儲存push命令時的那一刻的最小值,因為棧只有一個口是可以進行寫入和彈出的,所以,在寫入的那一時刻,最小值是不會變的,在pop的時候,判斷一下這個pop的值是不是當前的最小值,如果是,也把儲存最小值的輔助棧pop一下,這樣操作完事之後,最小值還是輔助棧的最外面那個值。有點羅嗦,看程式碼

class MinStack
{
    private $array;
    private $minArray;
    private $top;
    private $min;

    /**
     * initialize your data structure here.
	 * TODO: 我是使用陣列函式進行實現的,因為我覺得用php裡面原聲的棧函式很low哈哈哈(new SplStack())
     */
    function __construct() {
        $this->array    = [];
        $this->
minArray = []; $this->top = null; $this->min = null; } function push(int $x) { if (($this->min !== null && $this->min >= $x) || $this->min === null) { $this->min = $x; array_push($this->minArray, $x); } $this->top = $x; array_push($this->array, $x); return null; } function pop() { if (!$this->array) return null; $now = array_pop($this->array); if ($now == $this->min) { array_pop($this->minArray); if ($this->minArray) { $this->min = array_pop($this->minArray); array_push($this->minArray, $this->min); } else { $this->min = null; } } if ($this->array) { $this->top = array_pop($this->array); array_push($this->array, $this->top); } return $now; } function top() { return $this->top; } function getMin() { return $this->min; } }

在這裡插入圖片描述