剑指Offer-Java-包含min函数的栈

包含min函数的栈


题目:
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
代码:

package com.sjsq.test;

/**
 * @author shuijianshiqing
 * @date 2020/5/22 22:20
 */

import java.util.Stack;

/**
 * 定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素
 * 的min函数(时间复杂度应为O(1))。
 * 注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
 */


public class Solution {

    Stack<Integer> stack = new Stack<Integer>();
    // 设置一个临时栈来存放被pop出的数据
    Stack<Integer> tmp = new Stack<Integer>();

    public void push(int node) {
        stack.push(node);
    }

    public void pop() {
        stack.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int min() {
        int min = Integer.MAX_VALUE;
        // 出栈
        while(stack.isEmpty() != true){
            int node = stack.pop();
            if(min > node){
                min = node;
            }
            tmp.push(node);
        }
        // 进栈
        while(tmp.isEmpty() != true){
            stack.push(tmp.pop());
        }
        return min;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章