码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Min Stack

时间:2015-10-24 00:08:58      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:(链接)

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.

解题思路:

 1 class MinStack {
 2 public:
 3     void push(int x) {
 4         elems.push(x);
 5         if (minElems.empty() || minElems.top() >= x) {
 6             minElems.push(x);
 7         }
 8     }
 9 
10     void pop() {
11         if (elems.top() == minElems.top()) {
12             minElems.pop();
13         }
14         elems.pop();
15     }
16 
17     int top() {
18         return elems.top();
19     }
20 
21     int getMin() {
22         return minElems.top();
23     }
24 private:
25     stack<int> elems;
26     stack<int> minElems;
27 };

 

[LeetCode]Min Stack

标签:

原文地址:http://www.cnblogs.com/skycore/p/4905939.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!