牛客题霸NC90设计getMin功能的栈Java题解

牛客题霸NC90设计getMin功能的栈Java题解

https://www.nowcoder.com/practice/c623426af02d4c189f92f2a99647bd34?tpId=117&&tqId=35012&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking

方法:利用辅助栈
解题思路:利用两个栈stackA和stackB,stackA中存储所有元素并负责入栈push()和出栈pop()操作。stackB中存储stackA中所有非严格降序的元素,stackA中最小的元素对应stackB中的栈顶元素。

import java.util.*;
 
 
public class Solution {
    /**
     * return a array which include all ans for op3
     * @param op int整型二维数组 operator
     * @return int整型一维数组
     */
    Stack<Integer> stackA = new Stack<>();       
    Stack<Integer> stackB = new Stack<>();       //用于存储栈A中所有非严格降序的元素
    ArrayList<Integer> tmp = new ArrayList<>();  //用于存储栈中的最小值
 
    public int[] getMinStack (int[][] op) {
        for(int[] option : op){
            if(option[0]==1){        //如果当前是push操作
                push(option[1]);
            }else if(option[0]==2){  //如果当前是pop()操作
                pop();
            }else{                   //如果当前是getMin()操作
                int min = getMin();
                tmp.add(min);
            }
        }
 
        int[] res = new int[tmp.size()];
 
        for(int i = 0;i< res.length;i++){  //将ArrayList中的元素转存到res数组中,返回
            res[i] = tmp.get(i);
        }
 
        return res;
    }
 
    public void push(int x) {         
        stackA.add(x);                //将x压入stackA中
        if(stackB.isEmpty()){         //如果stackB为空,直接压入stackB中
            stackB.add(x);
        }else{                        //如果stackB不为空,且x<=stackB栈顶的元素,则将x压入stackB中
            if(x<=stackB.peek()){       
                stackB.add(x);
            }
        }
    }
 
    public void pop() {
        int i = stackA.pop();       //将stackA栈顶的元素弹出
        if(i==stackB.peek()){       //如果stackA中弹出的栈顶元素等于stackB中栈顶的元素,则弹出stackB中栈顶的元素
            stackB.pop();
        }
    }
 
    public int getMin() {    //stackB中存储stackA中都有非严格降序的元素,所以stackA中最小元素对应stackB的栈顶元素。         
        return stackB.peek();
    }
}

 

posted @ 2020-11-26 22:56  云飞扬°  阅读(115)  评论(0编辑  收藏  举报