[LeetCode]Min Stack,解题报告
2015-03-02 12:17
267 查看
目录
目录题目
思路1
AC代码
缺陷
思路2
AC代码
题目
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.
思路1
这道题算是面试过程中比较简单的题目,在实现基础栈的基础上,增加了一个在O(1)时间复杂度下获取当前栈内最小值的需求。很自然的可以想到,可以用ArrayList来构建stack,同时用一个int类型的变量minIndex作为当前最小值的下标。
每次push(x)操作时,判断是否需要更新minIndex。
每次pop操作时,判断当前移除的是否为minIndex,如果是,则需要O(n)时间复杂度更新minIndex。
思路有了,我们可以先写代码尝试一下,这种思路是否可以AC这道题目。
AC代码
import java.util.ArrayList; public class MinStack { private ArrayList<Integer> stack = new ArrayList<Integer>(); private int minIndex = 0; public void push(int x) { stack.add(x); if (x < stack.get(minIndex) || stack.size() == 1) { minIndex = stack.size() - 1; } } public void pop() { if (minIndex == stack.size() - 1) { minIndex = 0; for (int i = 1; i < stack.size() - 1; i ++) { if (stack.get(i) < stack.get(minIndex)) { minIndex = i; } } } stack.remove(stack.size() - 1); } public int top() { return stack.get(stack.size() - 1); } public int getMin() { return stack.get(minIndex); } }
缺陷
虽然上面的代码可以AC,而且getMin()方法的时间复杂度是O(1),但是我们在pop方法中,当需要更新minIndex时,花费的时间复杂度是O(n),严格的说,上面的代码是不符合面试要求的。减少时间复杂度最便捷的方法就是增加空间复杂度,很自然的我们想到“双栈法”。再维护一个最小数的栈,这样更新minIndex的操作我们可以通过最小数出栈的方式来搞定了。
思路2
双栈法的思路是:增加一个最小栈。当最小栈为空或者当前push元素小于等于最小栈栈顶元素时,该push元素也要push到最小栈中。AC代码
import java.util.Stack; public class MinStack { private Stack<Integer> normalStack = new Stack<Integer>(); private Stack<Integer> minStack = new Stack<Integer>(); public void push(int x) { if (minStack.size() == 0 || x <= minStack.peek()) { minStack.push(x); } normalStack.push(x); } public void pop() { if (normalStack.peek().equals(minStack.peek())) { minStack.pop(); } normalStack.pop(); } public int top() { return normalStack.peek(); } public int getMin() { return minStack.peek(); } }
相关文章推荐
- LeetCode-Min Stack-解题报告
- 【LeetCode】Min Stack 解题报告
- 【LeetCode】Min Stack 解题报告
- 【LeetCode】Min Stack 解题报告
- Leetcode 400. Nth Digit 第n个数字 解题报告
- 解题报告:LeetCode Search in Rotated Sorted Array II(循环数字查找)
- LeetCode(173) Binary Search Tree Iterator解题报告
- 【LeetCode】Partition List 解题报告
- LeetCode 513. Find Bottom Left Tree Value 解题报告
- [leetcode] 360. Sort Transformed Array 解题报告
- LeetCode Merge k Sorted Lists 解题报告
- 【LeetCode】Trapping Rain Water解题报告
- [Leetcode] 144. Binary Tree Preorder Traversal 解题报告
- [leetcode] 78. Subsets 解题报告
- [leetcode] 361. Bomb Enemy 解题报告
- 【LeetCode #179】Largest Number 解题报告
- leetcode 377. Combination Sum IV 解题报告
- [Leetcode] 148. Sort List 解题报告
- [leetcode] 3. Longest Substring Without Repeating Characters 解题报告
- [Leetcode] 41. First Missing Positive 解题报告