生活随笔
收集整理的這篇文章主要介紹了
常考数据结构与算法:设计getMin功能的栈
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目描述
實(shí)現(xiàn)一個(gè)特殊功能的棧,在實(shí)現(xiàn)棧的基本功能的基礎(chǔ)上,再實(shí)現(xiàn)返回棧中最小元素的操作。
?
示例1
輸入
[[1,3],[1,2],[1,1],[3],[2],[3]]
返回值
[1,2]
備注:
有三種操作種類,op1表示push,op2表示pop,op3表示getMin。你需要返回和op3出現(xiàn)次數(shù)一樣多的數(shù)組,表示每次getMin的答案1<=操作總數(shù)<=1000000
-1000000<=每個(gè)操作數(shù)<=1000000
數(shù)據(jù)保證沒有不合法的操作
?
方法:利用輔助棧
解題思路:利用兩個(gè)棧stackA和stackB,stackA中存儲(chǔ)所有元素并負(fù)責(zé)入棧push()和出棧pop()操作。stackB中存儲(chǔ)stackA中所有非嚴(yán)格降序的元素,stackA中最小的元素對(duì)應(yīng)stackB中的棧頂元素。
import java.util.ArrayList;
import java.util.Stack;public class MinStackMe {public static void main(String[] args) {MinStackMe minStackMe = new MinStackMe();int[][] arr = {{1,3},{1,2},{1,1},{3},{2},{3}};}private Stack<Integer> stackA = new Stack<>();private Stack<Integer> stackB = new Stack<>();private ArrayList<Integer> res = new ArrayList<>();/**** [1,3],[1,2],[1,1],[3],[2],[3]*** return a array which include all ans for op3* @param op int整型二維數(shù)組 operator* @return int整型一維數(shù)組*/public int[] getMinStack (int[][] op) {if(null == op){return null;}for (int i = 0; i < op.length; i++) {switch(op[i][0]){case 1:push(op[i][1]);break;case 2:pop();break;default:res.add(getMin());break;}}int ret[] = new int[res.size()];for (int i = 0; i < res.size(); i++) {ret[i] = res.get(i);//System.out.println(ret[i]);}return ret;}private void push(int x){stackA.push(x); //將x壓入stackA中if(stackB.isEmpty()){ //如果stackB為空,直接壓入stackB中stackB.push(x);}else{//如果stackB不為空,且x<=stackB棧頂?shù)脑?#xff0c;則將x壓入stackB中if(stackB.peek() >= x){stackB.push(x);}}}private int pop(){int x = 0;if(!stackA.isEmpty()){x = stackA.pop();}//如果stackA中彈出的棧頂元素等于stackB中棧頂?shù)脑?#xff0c;則彈出stackB中棧頂?shù)脑豬f(x == stackB.peek()){stackB.pop();}return x;}public int getMin() { //stackB中存儲(chǔ)stackA中都有非嚴(yán)格降序的元素,所以stackA中最小元素對(duì)應(yīng)stackB的棧頂元素。return stackB.peek();}
}
?
總結(jié)
以上是生活随笔為你收集整理的常考数据结构与算法:设计getMin功能的栈的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。