05 设计getMin功能的栈
Table of Contents

ac

import java.util.Scanner;
import java.util.Stack;

class MinStack{
    Stack<Integer> sta = new Stack<>();
    Stack<Integer> staMin = new Stack<>();

    void push(int val){
        if(sta.isEmpty()){
            sta.push(val);
            staMin.push(val);
        }else {
            int curMin = staMin.peek();
            if(val < curMin){
                sta.push(val);
                staMin.push(val);
            }else {
                sta.push(val);
                staMin.push(curMin);
            }
        }
    }

    int getMin(){
        int curMin = staMin.peek();
        return curMin;
    }

    void pop(){
        sta.pop();
        staMin.pop();
    }

}

public class Main {

    public static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        int n = sc.nextInt();
        MinStack minStack = new MinStack();
        for(int i=0;i<n;i++){
            String s = sc.next();
            if(s.equals("push")){
                int val = sc.nextInt();
                minStack.push(val);
            }else if(s.equals("getMin")){
                int minVal = minStack.getMin();
                System.out.println(minVal);
            }else if(s.equals("pop")){
                minStack.pop();
            }
        }
    }

}

栈顶部:存最小值,接着的位置:存储当前元素与上个最小值的差

import java.util.Scanner;
import java.util.Stack;

class MinStack{
    Stack<Integer> sta = new Stack<>();

    void push(int val){
        if(sta.isEmpty()){
            sta.push(0);
            sta.push(val);
        }else {
            int curMin = sta.peek();
            int diff = val - curMin;
            if(diff <= 0){
                sta.push(diff);
                sta.push(val);
            }else {
                sta.push(diff);
                sta.push(curMin);
            }
        }
    }

    int getMin(){
        int curMin = sta.peek();
        return curMin;
    }

    void pop(){
        sta.pop();
        sta.pop();
        /**
         * eg:
         *
         * 3 2 1: 0 3 -1 2, 0 3 -1 2 -1 1
         * 3 1 2: 0 3 -2 1, 0 3 -2 1 1 1
         */
    }

}

public class Main {

    public static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        int n = sc.nextInt();
        MinStack minStack = new MinStack();
        for(int i=0;i<n;i++){
            String s = sc.next();
            if(s.equals("push")){
                int val = sc.nextInt();
                minStack.push(val);
            }else if(s.equals("getMin")){
                int minVal = minStack.getMin();
                System.out.println(minVal);
            }else if(s.equals("pop")){
                minStack.pop();
            }
        }
    }

}