[Easy] 155. Min Stack
发布日期:2021-05-07 18:21:25 浏览次数:22 分类:精选文章

本文共 1399 字,大约阅读时间需要 4 分钟。

155. Min Stack

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.

Example 1:

Input["MinStack","push","push","push","getMin","pop","top","getMin"][[],[-2],[0],[-3],[],[],[],[]]Output[null,null,null,null,-3,null,0,-2]ExplanationMinStack minStack = new MinStack();minStack.push(-2);minStack.push(0);minStack.push(-3);minStack.getMin(); // return -3minStack.pop();minStack.top();    // return 0minStack.getMin(); // return -2

Constraints:

Methods pop, top and getMin operations will always be called on non-empty stacks.

Solution

Runtime: 48 ms, faster than 23.55% of C++ online submissions for Min Stack.

Memory Usage: 16.1 MB, less than 100.00% of C++ online submissions for Min Stack.

class MinStack {   private:    stack
s1, s2;public: /** initialize your data structure here. */ MinStack() { } void push(int x) { if(s2.empty() || x <= getMin()) s2.push(x); s1.push(x); } void pop() { if(s1.top()==getMin()) s2.pop(); s1.pop(); } int top() { return s1.top(); } int getMin() { return s2.top(); }};

使用双栈,一个存放当前最小元素,另一个存放所有元素。

入栈时,需要考虑是否是当前最小,出栈时,需要考虑两个栈是否都需出栈。

上一篇:[Easy] 160. Intersection of Two Linked Lists
下一篇:[Easy] 141. Linked List Cycle

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年03月28日 00时08分19秒