多味的LeetCode --- 面試題 03.02. 棧的最小值

題目描述:

  請設計一個棧,除了常規棧支持的pop與push函數以外,還支持min函數,該函數返回棧元素中的最小值。執行push、pop和min操作的時間複雜度必須爲O(1)。

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

解題思路:

開一個最小棧minstack,棧頂存放的是已經出現的最小元素。當壓入的時候,比較需要壓入的值x與棧頂的大小


代碼:

python寫法:

class MinStack:

    def __init__(self):
        self.stack = []
        self.minstack = []

    def push(self, x):
        self.stack.append(x)
        if len(self.minstack) == 0 or x <= self.minstack[-1]:
            self.minstack.append(x)

    def pop(self):
        if self.stack.pop() == self.minstack[-1]:
            self.minstack.pop()

    def top(self):
        return self.stack[-1]

    def getMin(self):
        return self.minstack[-1]

c++寫法:

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> stk, stk_min;
    MinStack() {
        
    }
    
    void push(int x) {
        stk.push(x);
        if (stk_min.empty()) stk_min.push(x);
        else stk_min.push(min(x, stk_min.top()));
    }
    
    void pop() {
        stk.pop();
        stk_min.pop();
    }
    
    int top() {
        return stk.top();
    }
    
    int getMin() {
        return stk_min.top();
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章