IT公司100题-2-设计带min函数的stack

问题描述:

定义栈的数据结构,要求添加一个min 函数,能够得到栈的最小元素。

要求函数min、push 以及pop 的时间复杂度都是O(1)。

 

双倍空间实现:

保存2个栈,分别是元素和当前最小值。

 

压缩空间实现:

代码实现:

package oschina.IT100;
/**
 * @project: oschina
 * @filename: IT2.java
 * @version: 0.10
 * @author: JM Han
 * @date: 17:08 2015/10/20
 * @comment: design a stack that has min function which could return the min element at anytime
 * @result:
 */

import java.util.Stack;

class MinStack{
   Stack<Integer> stacks, mins;
   MinStack(){
      stacks = new Stack<Integer>();
      mins   = new Stack<Integer>();
   }
   void push(Integer x){
      stacks.push(x);
      //use <= instead of < for duplicate element
      if(mins.isEmpty() || x <= mins.peek())
         mins.push(x);
   }
   void pop(){
      Integer x = stacks.pop();
      if(x == mins.peek())
         mins.pop();
   }
   Integer peek(){
      return stacks.peek();
   }
   Integer getMin(){
      return mins.peek();
   }
}

public class IT2 {
   public static void main(String[] args) {
      MinStack minStack = new MinStack();
      minStack.push(6);
      minStack.push(2);
      minStack.push(3);
      minStack.push(1);
      minStack.push(1);
      minStack.push(5);
      minStack.push(8);
      System.out.println("Content of stack: \n" + minStack.stacks);
      System.out.println("min value of stack: \n" + minStack.getMin());
      System.out.println("Content of mins: \n" + minStack.mins);
      minStack.pop();
      minStack.pop();
      minStack.pop();
      System.out.println("Content of mins: \n" + minStack.mins);
      System.out.println("min value of stack: \n" + minStack.getMin());
   }
}

 输出:

Content of stack: 
[6, 2, 3, 1, 1, 5, 8]
min value of stack: 
1
Content of mins: 
[6, 2, 1, 1]
Content of mins: 
[6, 2, 1]
min value of stack: 
1


转载于:https://my.oschina.net/jimmyhan/blog/519467

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值