categories: leetcode


155.png

题目描述

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.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); —> Returns -3.
minStack.pop();
minStack.top(); —> Returns 0.
minStack.getMin(); —> Returns -2.

参考代码

  1. class MinStack {
  2. private Stack<Integer> stackData;
  3. private Stack<Integer> stackMin;
  4. /** initialize your data structure here. */
  5. public MinStack() {
  6. stackData = new Stack<Integer>();
  7. stackMin = new Stack<Integer>();
  8. }
  9. public void push(int x) {
  10. stackData.push(x);
  11. if(stackMin.isEmpty() || x <= stackMin.peek()) {//最小值栈的为空或这最小值小于等于
  12. stackMin.push(x);
  13. }
  14. }
  15. public void pop() {
  16. Integer num = stackData.pop();
  17. if(num.equals(stackMin.peek())) {//要用equals函数
  18. stackMin.pop();
  19. }
  20. }
  21. public int top() {
  22. return stackData.peek();
  23. }
  24. public int getMin() {
  25. return stackMin.peek();
  26. }
  27. }
  28. /**
  29. * Your MinStack object will be instantiated and called as such:
  30. * MinStack obj = new MinStack();
  31. * obj.push(x);
  32. * obj.pop();
  33. * int param_3 = obj.top();
  34. * int param_4 = obj.getMin();
  35. */

思路及总结

利用两个栈,一个代表最小值,一个代表普通情况。注意最小值栈要依靠普通栈,普通栈中最小值出栈,最小值栈的最小值也要出栈。另外自己基础太差,wrong answer的时候一直没发现要用equals才能进行更合理的比较。希望自己以后更深入的时候能有更好的理解。
image.png

参考

https://blog.csdn.net/loophome/article/details/83749444
https://blog.csdn.net/returnzhang/article/details/78608898