面試題精選(80):設計含min函數的棧的另解

來源:互聯網
上載者:User

題目:定義棧的資料結構,要求添加一個min函數,能夠得到棧的最小元素。要求函數min、push以及pop的時間複雜度都是O(1)。

 

分析:

 

下面給出的連結是之前使用雙倍空間2*n來實現的

http://blog.csdn.net/yysdsyl/archive/2007/10/24/1841644.aspx

 

其實,輔助棧的使用可以進一步最佳化,做到worst-case下使用n空間,從而更大程度上節省空間的:

 

template <typename T> class MinStack {
    stack<T> _stack, _min;

public:
    MinStack() { }

    void push(const T & x) {
        _stack.push(x);
        if (_min.empty() || !(x < _min.top())) _min.push(x);
    }

    T pop() {
        T x = _stack.top();
        _stack.pop();
        if (x == _min.top()) _min.pop();
        return T;
    }

    T getMin() {
        return _min.top();
    }
};

 

 

 

不過即使在輔助棧的使用上作了必要的最佳化,但是空間的使用在worst-case下依舊是個問題,那麼有沒有更好的解決辦法呢?下面將給出一個O(n+1)空間複雜度的設計方法:(用diff來壓縮)

void push(int elem) {
    if (stack.empty()) {
        stack.push(elem);
        stack.push(elem);
    } else {
        int min = stack.pop();
        stack.push(elem - min);
        stack.push(elem < min ? elem: min);
    }
}

 

int pop() {
    int min = stack.pop(), elem = stack.pop();
    if (elem < 0) {
        stack.push(min - elem);
        return min;
    } else {
        if (!stack.empty()) stack.push(min);
        return elem + min;
    }
}

 

int min() const {
    int min = stack.pop();
    stack.push(min);
    return min;
}

 

過程類比:

clear(): [ ]
push(3): [3 3]
push(4): [3 1 3]
push(2): [3 1 -1 2]
push(5): [3 1 -1 3 2]
push(1): [3 1 -1 3 -1 1]
push(1): [3 1 -1 3 -1 0 1]
push(6): [3 1 -1 3 -1 0 5 1]
push(7): [3 1 -1 3 -1 0 5 6 1]

min() --> 1; pop() --> 7: [3 1 -1 3 -1 0 5 1]
min() --> 1; pop() --> 6: [3 1 -1 3 -1 0 1]
min() --> 1; pop() --> 1: [3 1 -1 3 -1 1]
min() --> 1; pop() --> 1: [3 1 -1 3 2]
min() --> 2; pop() --> 5: [3 1 -1 2]
min() --> 2; pop() --> 2: [3 1 3]
min() --> 3; pop() --> 4: [3 3]
min() --> 4; pop() --> 3: [ ]

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.