剑指 Offer 30. 包含min函数的栈
Posted taoyuxin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指 Offer 30. 包含min函数的栈相关的知识,希望对你有一定的参考价值。
public class MinStack { /** initialize your data structure here. */ Stack<Integer> stack = new Stack<>(); private int min = Integer.MIN_VALUE; List<Integer> list = new ArrayList<>(); public MinStack() { } public void push(int x) { stack.push(x); if(list.isEmpty()){ list.add(x); min = x; }else{ if(list.get(0) >= x){ list.add(0,x); min = x; }else{ int i = 1; while (i<list.size() && list.get(i) < x){ i++; } if(i == list.size()){ list.add(x); }else{ list.add(i,x); } } } } public void pop() { int pop = stack.pop(); for(int i = 0;i<=list.size();i++){ if(list.get(i) == pop){ list.remove(i); if(i == 0) { if(list.isEmpty()){ min = Integer.MIN_VALUE; }else { min = list.get(0); } } break; } } } public int top() { return stack.peek(); } public int min() { return min; }
方法二:
class MinStack { /** initialize your data structure here. */ Stack<Integer> stack = new Stack<>(); Stack<Integer> stack_temp = new Stack<>(); public MinStack() { } public void push(int x) { stack.push(x); if(stack_temp.isEmpty()){ stack_temp.add(x); }else{ if(stack_temp.peek() >= x){ stack_temp.push(x); }else{ stack_temp.push(stack_temp.peek()); } } } public void pop() { stack.pop(); stack_temp.pop(); } public int top() { return stack.peek(); } public int min() { if(stack_temp.isEmpty()){ return Integer.MIN_VALUE; }else{ return stack_temp.peek(); } } }
以上是关于剑指 Offer 30. 包含min函数的栈的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode(剑指 Offer)- 30. 包含min函数的栈