标签:min off alt lis stack ini rem sem you
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(); } } }
标签:min off alt lis stack ini rem sem you
原文地址:https://www.cnblogs.com/taoyuxin/p/13472421.html