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

剑指offer-包含min函数的栈

时间:2020-02-21 22:18:34      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:一个   时间   java   元素   turn   col   describe   时间复杂度   class   

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);
        if(stack2.empty())
            stack2.push(node);
        if(node<stack2.peek())
            stack2.push(node);
        
    }
    
    public void pop() {
        if(stack1.peek()==stack2.peek()){
            stack1.pop();
            stack2.pop();
        }
        else{
            stack1.pop();
        }
        
    }
    
    public int top() {
        return stack1.peek();
        
    }
    
    public int min() {
        return stack2.peek();
        
    }
}

 

剑指offer-包含min函数的栈

标签:一个   时间   java   元素   turn   col   describe   时间复杂度   class   

原文地址:https://www.cnblogs.com/loyolh/p/12343102.html

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