LeetCode第155题解析

设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。

示例:

输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2]

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

解法一:

用两个栈,一个数据栈,一个存放最小值的辅助栈。

class MinStack {
public:
	/** initialize your data structure here. */
	MinStack() {
		dataStack = {};
		minStack = {};
	}

	void push(int x) {
		dataStack.push(x);
        //minStack.push(min(x, minStack.top()));
		if (minStack.empty() || minStack.top() >= x) {
			minStack.push(x);
		}
	}
	void pop() {
		if (dataStack.top() == minStack.top()) {
			minStack.pop();
		}
		dataStack.pop();
	}

	int top() {
		return dataStack.top();
	}

	int getMin() {
		return minStack.top();
	}

private:
	stack dataStack;
	stack minStack;
};

解法二:

栈中存放pair,包含最小值。

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        minStack = { };
    }
    
    void push(int x) {
        if (minStack.empty() || minStack.top().second >= x) {
            minStack.push(make_pair(x, x));
        }
        else {
            minStack.push(make_pair(x, minStack.top().second));
        }
    }
    
    void pop() {
        minStack.pop();
    }
    
    int top() {
        return minStack.top().first;
    }
    
    int getMin() {
        return minStack.top().second;
    }
private:
    stack> minStack;
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack* obj = new MinStack();
 * obj->push(x);
 * obj->pop();
 * int param_3 = obj->top();
 * int param_4 = obj->getMin();
 */

解法三:

自定义一个栈,用链表来实现。

class MinStack {
public:
    /** initialize your data structure here. */
private:
    struct Node {
        //要记得初始化
        int value = 0;
        int m_min = INT_MAX;
        Node * next = nullptr;
    };
public:
    Node * head = new Node;
    MinStack() {

    }
    
    void push(int x) {
        Node * node = new Node;
        node->value = x;
        node->m_min = min(x, head->m_min);
        node->next = head;
        //要记得更换头结点
        head = node;
    }
    
    void pop() {
        head = head->next;
    }
    
    int top() {
        return head->value;
    }
    
    int getMin() {
        return head->m_min;
    }
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack* obj = new MinStack();
 * obj->push(x);
 * obj->pop();
 * int param_3 = obj->top();
 * int param_4 = obj->getMin();
 */

 

你可能感兴趣的:(LeetCode)