标签:queue remove else append comm and ons var pos
设计支持push、pop、top和在常量时间内检索最小元素的栈。
push(x) —— 推送元素X进栈
pop() —— 移除栈顶元素
top() —— 得到栈顶元素
getMin() —— 检索栈的最小元素Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.之前写过两道题,各自是用Stack来实现Queue的功能以及用Queue来实现Stack的功能,这里假设也使用两个Stack的话就很easy了。
LeetCode 225 Implement Stack using Queues(用队列来实现栈)(*)
LeetCode 232 Implement Queue using Stacks(用栈来实现队列)(*)
class MinStack {
public:
    stack<int> allStack;
    stack<int> minSta;
    void push(int x) {
        if (allStack.empty()) {
            allStack.push(x);
            minSta.push(x);
        }
        else {
            allStack.push(x);
            if (x <= minSta.top()) minSta.push(x);
        }
    }
    void pop() {
        if (allStack.top() == minSta.top()) {
            minSta.pop();
        }
        allStack.pop();
    }
    int top() {
        return allStack.top();
    }
    int getMin() {
        return minSta.top();
    }                                  
};除了上面的stack,我还用vector实现了:
class MinStack {
public:
    vector<int> allVec;
    vector<int> minVec;
    void push(int x) {
        if (allVec.empty()) {       
            allVec.push_back(x);
            minVec.push_back(x);
        }
        else {
            if (x <= minVec[minVec.size() - 1]) {
                minVec.push_back(x);
            }
            allVec.push_back(x);
        }
    }
    void pop() {
        if (allVec[allVec.size() - 1] == minVec[minVec.size() - 1])
            minVec.erase(minVec.end() - 1);
        allVec.erase(allVec.end() - 1);
    }
    int top() {
        return allVec[allVec.size() - 1];
    }
    int getMin() {
        return minVec[minVec.size() - 1];
    }
};然而用vector效率反而更低了……
标签:queue remove else append comm and ons var pos
原文地址:http://www.cnblogs.com/lytwajue/p/7289237.html