题解 | #设计getMin功能的栈#

设计getMin功能的栈

http://www.nowcoder.com/practice/c623426af02d4c189f92f2a99647bd34

import java.util.*;

public class Solution {
/**
* return a array which include all ans for op3
* @param op int整型二维数组 operator
* @return int整型一维数组
*/
public static Stack<integer>s = new Stack<integer>();//s用来存数据
public static Stack<integer>min_s = new Stack<integer>();//min_s用来获取最小值
public int[] getMinStack (int[][] op) {
// write code here
ArrayList<integer> res = new ArrayList<integer>();//结果集
for (int i = 0;i<op.length;i++){
if (op[i][0] == 1){ //为1就入栈
Push(op[i][1]);
}else if (op[i][0] == 2){//为2就出栈
Pop();
}else//为3就返回栈中最小元素
res.add(getMin());
}
//因为返回类型的缘故我们需要把res中的元素丢在arr数组里面
int [] arr = new int[res.size()];
for (int i = 0;i< res.size();i++){
arr[i] = res.get(i);
}
return arr;</integer></integer></integer></integer></integer></integer>

}
public void Push(int x){
    s.push(x);
    if(min_s.empty() || min_s.peek()>=x)min_s.push(x); //如果min_s为空,或者栈顶元素大于x就进入min_s
}
public void Pop() {
    if(!s.empty()){
        if(s.peek().equals(min_s.peek())) min_s.pop();//如果min_s栈顶元素和栈s中要出栈的元素相等,那么也需要出栈
        s.pop();
    }  

}
int getMin(){
    return min_s.peek();//栈min_s的栈顶元素即为最小值
}

}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务