155. Min Stack

xiaoxiao2021-02-28  44

1,题目要求 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. 设计一个栈,可以返回栈中最小的元素。

2,题目思路 具体实现不难,一开始直接用vector来去实现,最后是AC但是时间耗费太长了。 参考过后,发现实现这个栈可以另外定义栈去实现。。。 定义两个栈,一个正常存储元素,另一个存储当前的最小值:因为pop操作会导致整个栈中的最小值发生能改变,因此需要一个栈来记录当前栈中的最小值。 当pop操作的值等于当前最小栈的top值,最小栈也需要进行pop操作来对整个栈最小的更新。

3,程序源码

class MinStack { public: /** initialize your data structure here. */ MinStack() { } void push(int x) { s1.push(x); if(s2.empty() || s2.top()>=x) s2.push(x); } void pop() { if(s2.top() == s1.top()) s2.pop(); s1.pop(); } int top() { return s1.top(); } int getMin() { return s2.top(); } private: stack<int> s1; stack<int> s2; };
转载请注明原文地址: https://www.6miu.com/read-2629793.html

最新回复(0)