Min Stack, minstack
Original question link: https://oj.leetcode.com/problems/min-stack/
This question is about the stack. It implements the basic functions of a stack and an operation to obtain the minimum element. Under normal circumstances, the top, pop, and push operations are constant time, and the main problem is that the getMin is above. If the minimum value is searched through traversal, The getMin operation is O (n, this question is certainly not that simple. It is easy to think that the minimum value should be traced back, and the minimum value should be maintained during push. But what should I do if the pop gets the minimum value? How can I get the second small value? If you are looking for it, it is not a constant time. The solution is to maintain another stack, which is called the minimum stack. If a value is smaller, insert the minimum stack, otherwise, you do not need to insert the minimum stack (note how the normal Stack is inserted here ). The correctness here is that if the value obtained later is greater than the value of the current minimum stack top, then pop will go out first, and the value of the minimum stack top will remain, when pop reaches the minimum stack top value, the second smallest value is the top of the minimum stack after pop. In this way, one element of two stacks can be inserted at most, which is O (1), top is the top of the normal stack, and naturally it is O (1 ), in pop mode, at most two stacks of top elements are thrown: O (1 ). Finally, getMin only needs the smallest stack top stack of peek, so it is still O (1), which implements constant operations for all operations. The space complexity is O (n), and the minimum stack size. The Code is as follows:
class MinStack { ArrayList<Integer> stack = new ArrayList<Integer>(); ArrayList<Integer> minStack = new ArrayList<Integer>(); public void push(int x) { stack.add(x); if(minStack.isEmpty() || minStack.get(minStack.size()-1)>=x) { minStack.add(x); } } public void pop() { if(stack.isEmpty()) { return; } int elem = stack.remove(stack.size()-1); if(!minStack.isEmpty() && elem == minStack.get(minStack.size()-1)) { minStack.remove(minStack.size()-1); } } public int top() { if(!stack.isEmpty()) return stack.get(stack.size()-1); return 0; } public int getMin() { if(!minStack.isEmpty()) return minStack.get(minStack.size()-1); return 0; }}
After clarifying the idea, the code is still relatively simple. Here we use ArrayList to implement the stack. Of course we can also use the linked list, but it requires a high level of time complexity, therefore, the key point is to come up with the practice of maintaining the minimum stack top, which is a good interview question for the nature of the site. It often appears in the face-to-face experience.