[LeetCode]155. Min Stack
2016-03-06 10:09
288 查看
Problem Description
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.
[]https://leetcode.com/problems/min-stack/]
思路
TLE版:维护两个LinkedList,一个按顺序排列,一个按栈排列。插入时用二分查找找位置。大神版:栈里保存an=bn-min{an-1……….0};bn是真正压栈的数。
[]https://leetcode.com/discuss/15679/share-my-java-solution-with-only-one-stack]
Code
package q155; import java.util.Stack; public class MinStack { private static Stack<Long> s; public MinStack() { s = new Stack<Long>(); } private static long min = (long) Integer.MIN_VALUE; public static void push(int x) { if (s.isEmpty()) { min = (long) x; s.push(0L); } else { if (min >= x) { s.push(x - min); min = (long) x; } else { s.push(x - min); } } } public static void pop() { if (!s.isEmpty()) { long tmp = s.pop(); if (tmp < 0) min = min - tmp; } } public static int top() { if (!s.isEmpty()) { long tmp = s.peek(); if (tmp > 0) return (int) (min + tmp); else return (int) (min); } return -1; } public static int getMin() { return (int) min; } // public static void main(String[] args) { // // MinStack.push(-1); // System.out.print(MinStack.top()); // System.out.print(MinStack.getMin()); // } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解