首页 > 其他 > 详细

实现stack 加上·getMin功能 时间复杂度为O(n)

时间:2017-04-25 19:02:14      阅读:227      评论:0      收藏:0      [点我收藏+]
package com.hzins.suanfa;

import java.util.Stack;
/**
 * 实现stack 加上·getMin功能 时间复杂度为O(n)
 * @author Administrator
 *
 */
public class GetMinStack {
    private Stack<Integer> stackData;
    private Stack<Integer> stackMin;
    public GetMinStack(){
        this.stackData = new Stack<Integer>();
        this.stackMin = new Stack<Integer>();
    }
    public void push(int newNum){
        if(this.stackMin.isEmpty()){
            stackMin.push(newNum);
        }else if(newNum <this.getMin()){
            stackMin.push(newNum);
        }else{
            stackMin.push(this.getMin());
        }
        stackData.push(newNum);
    }
    public int pop(){
        if(stackData.isEmpty()){
            throw new RuntimeException("Your stack is empty");
        }
        stackMin.pop();
        return stackData.pop();
    }
    public int getMin(){
        if(this.stackMin.isEmpty()){
            throw new RuntimeException("Your stack is empty");
        }
        return this.stackMin.peek();
    }
}

 

实现stack 加上·getMin功能 时间复杂度为O(n)

原文:http://www.cnblogs.com/caobojia/p/6763702.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!