理解题目:获取栈内最小数字,那取出来排个序再放回去吧

1.用数组接,数组排序后第一个值就是最小的

  • 时间复杂度 2个循环
  • 空间复杂度 消耗了1个数组
import java.util.Stack;
import java.util.*;

public class Solution {

    Stack<Integer> stack1=new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);
    }
    
    public void pop() {
        if(!stack1.isEmpty())
            stack1.pop();
    }
    
    public int top() {
        return stack1.peek();
    }
    
    public int min() {
         int size = stack1.size();
        int min=0;
        int i=0;
        int[] num = new int[size];
        while(!stack1.isEmpty()){
            for(int j=0;j<size;j++)
                num[j]=stack1.pop();
        }
        if(num.length>=0){
            for(int j=size-1;j>=0;j--)
                stack1.push(num[j]);

            Arrays.sort(num);
            min=num[0];
        }
        return min;
    }
}

2.双栈思维,一个栈存储所有数,一个栈存储当前最小数

import java.util.Stack;
import java.util.*;

public class Solution {

    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    public void push(int node) {
        if(stack2.isEmpty()||stack2.peek()>=node)
            stack2.push(node);
        else
            stack2.push(stack2.peek());
        stack1.push(node);
    }
    
    public void pop() {
        stack2.pop();
        stack1.pop();
    }
    
    public int top() {
        return stack1.peek();
    }
    
    public int min() {
         return stack2.peek();
    }
}