首页 > 其他 > 详细

LeetCode Min Stack

时间:2014-11-18 06:52:34      阅读:253      评论:0      收藏:0      [点我收藏+]
#include <iostream>
#include <cstdlib>
#include <vector>

using namespace std;

class MinStack2 {
private:
    vector<pair<int, int> > mins;
    vector<int> stack;
public:
    void push(int x) {
        stack.push_back(x);
        if (mins.size() == 0) {
            mins.push_back(make_pair(x, 1));
        } else {
            int curr_min = mins.back().first;
            if (curr_min > x) {
                mins.push_back(make_pair(x, 1));
            } else if (curr_min == x) {
                mins.back().second++;
            } else {
                // do nothing
            }
        }
    }

    void pop() {
        if (!stack.size()) {
            return;
        }
        int x = stack.back();
        stack.pop_back();
        if (x == mins.back().first) {
            if (--mins.back().second < 1) {
                mins.pop_back();
            }
        } 
    }

    int top() {
        if (!stack.size()) {
            return 0;
        }
        return stack.back();
    }

    int getMin() {
        if (!stack.size()) {
            return 0;
        }
        return mins.back().first;
    }
};


class MinStack {
private:
    vector<int> mins;
    vector<int> stack;
public:
    void push(int x) {
        stack.push_back(x);
        if (mins.size() == 0) {
            mins.push_back(x);
        } else {
            if (mins.back() >= x) {
                mins.push_back(x);
            }
        }
    }

    void pop() {
        if (!stack.size()) {
            return;
        }
        
        if (stack.back() == mins.back()) {
            mins.pop_back();
        }
        stack.pop_back(); 
    }

    int top() {
        if (!stack.size()) {
            return 0;
        }
        return stack.back();
    }

    int getMin() {
        if (!stack.size()) {
            return 0;
        }
        return mins.back();
    }
};

int main() {
    MinStack stack;
    stack.push(3);
    stack.push(2);
    stack.push(3);

    cout<<stack.getMin()<<endl;
    stack.push(1);
    stack.push(1);
    cout<<stack.getMin()<<endl;
    stack.pop();
    stack.pop();
    cout<<stack.getMin()<<endl;
    return 0;
}

同样的逻辑用java版本的就对,C++就内存超出,难道是vector默认翻倍涨的原因?

LeetCode Min Stack

原文:http://www.cnblogs.com/lailailai/p/4104780.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!