首页 > 代码库 > Min Stack
Min Stack
Implement a stack with min() function, which will return the smallest number in the stack.
It should support push, pop and min operation all in O(1) cost.
Notice
min operation will never be called if there is no number in the stack.
Example
push(1) pop() // return 1 push(2) push(3) min() // return 2 push(1) min() // return 1
这道题也没什么好说的,只是要想到用两个stack实现,还要注意比较较的时候用equals比较好一点。
另外,比较的时候要有等号,如果都是最小值,要放多次。
public class MinStack { Stack<Integer> stack1; Stack<Integer> stack2; public MinStack() { stack1 = new Stack<>(); stack2 = new Stack<>(); } public void push(int number) { if (stack1.isEmpty()) { stack1.push(number); } else if (number <= stack1.peek()) { stack1.push(number); } stack2.push(number); } public int pop() { int tmp = stack2.pop(); if (stack1.peek().equals(tmp)) { stack1.pop(); } return tmp; } public int min() { return stack1.peek(); } }
Min Stack
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。