The sword refers to Offer-Java-the stack containing the min function

stack containing min function


Topic:
Define the data structure of the stack, please implement a min function in this type that can get the smallest element contained in the stack (the time complexity should be O(1)).
Note: Make sure that the test will not call pop() or min() or top() on the stack when the stack is empty.
Code:

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;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324130194&siteId=291194637