dmndxld

码不停题

栈应用:最小栈(第二题)

题目:

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

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

分析:

1.每次压入两个元素,一个是元素本身,另外一个进行判断,是否为最小,即存放当前栈最小值,代码实现如下

 1 /** initialize your data structure here. */
 2 public MinStack() {
 3     stack = new Stack<Integer>();
 4 }
 5 
 6 public void push(int x) {
 7     if(stack.isEmpty()){
 8         stack.push(x);
 9         stack.push(x);
10     }else{
11         int tmp = stack.peek();
12         stack.push(x);
13         if(tmp<x){
14             stack.push(tmp);
15         }else{
16             stack.push(x);
17         }
18     }
19 }
20 
21 public void pop() {
22     stack.pop();
23     stack.pop();
24 }
25 
26 public int top() {
27     return stack.get(stack.size()-2);
28 }
29 
30 public int getMin() {
31     return stack.peek();
32 }

为什么对着java版写不出来c++的呢?因为c++的stack类里面只有top()回栈顶,不能访问别的

2.用两个栈实现,一个压元素,一个压最小值,代码实现如下:

 1 class MinStack {
 2 public:
 3     stack<int> data;
 4     stack<int> minstack;
 5     /** initialize your data structure here. */
 6     MinStack() {
 7         
 8     }
 9     
10     void push(int x) {
11         data.push(x);
12         if(minstack.empty() || x <= minstack.top()){
13             minstack.push(x);
14         }
15     }
16     
17     void pop() {
18         if(data.top() == minstack.top()){
19             minstack.pop();
20         }                    //进行判断的原因很简单,data里面没有,对应的minstack里面也不应该存在
21         data.pop();
22     }
23     
24     int top() {
25         return data.top();
26     }
27     
28     int getMin() {
29         return minstack.top();
30     }
31 };

 

posted on 2019-04-15 20:54  imyourterminal  阅读(270)  评论(0编辑  收藏  举报

导航