题意:

image.png

解题思路:

  1. 思路:
  2. 1. 定义一个数据栈,存每次pushpoptop操作;
  3. 2. 再定义一个辅助栈,每次入栈元素跟辅助栈top元素比较下,如果比辅助栈栈顶元素小则入栈,大的话继续存辅助栈top元素;

图示未命名文件 (63).png

PHP代码实现:

  1. class MinStack {
  2. /**
  3. * initialize your data structure here.
  4. */
  5. private $top = -1;
  6. private $stack = [];
  7. private $minStack = [];
  8. function __construct() {
  9. $this->stack = [];
  10. $this->minStack = [];
  11. }
  12. /**
  13. * @param Integer $x
  14. * @return NULL
  15. */
  16. function push($x) {
  17. if ($this->top == -1) {
  18. array_push($this->stack, $x);
  19. array_push($this->minStack, $x);
  20. $this->top++;
  21. return true;
  22. }
  23. $min = $this->minStack[$this->top];
  24. $newMin = $x < $min ? $x : $min;
  25. array_push($this->stack, $x);
  26. array_push($this->minStack, $newMin);
  27. $this->top++;
  28. return true;
  29. }
  30. /**
  31. * @return NULL
  32. */
  33. function pop() {
  34. if ($this->top == -1) return false;
  35. array_pop($this->minStack);
  36. $this->top--;
  37. array_pop($this->stack);
  38. }
  39. /**
  40. * @return Integer
  41. */
  42. function top() {
  43. return $this->stack[$this->top];
  44. }
  45. /**
  46. * @return Integer
  47. */
  48. function getMin() {
  49. return $this->minStack[$this->top];
  50. }
  51. }
  52. /**
  53. * Your MinStack object will be instantiated and called as such:
  54. * $obj = MinStack();
  55. * $obj->push($x);
  56. * $obj->pop();
  57. * $ret_3 = $obj->top();
  58. * $ret_4 = $obj->getMin();
  59. */

GO代码实现:

  1. type MinStack struct {
  2. sk [] int
  3. minSk [] int
  4. }
  5. /** initialize your data structure here. */
  6. func Constructor() MinStack {
  7. return MinStack{}
  8. }
  9. func (this *MinStack) Push(x int) {
  10. if len(this.sk) == 0 || x <= this.GetMin() {
  11. this.minSk = append(this.minSk, x)
  12. }
  13. this.sk = append(this.sk, x)
  14. }
  15. func (this *MinStack) Pop() {
  16. if this.minSk[len(this.minSk)-1] == this.Top() {
  17. this.minSk = this.minSk[:len(this.minSk) - 1]
  18. }
  19. this.sk = this.sk[:len(this.sk) - 1]
  20. }
  21. func (this *MinStack) Top() int {
  22. return this.sk[len(this.sk) - 1]
  23. }
  24. func (this *MinStack) GetMin() int {
  25. return this.minSk[len(this.minSk)-1]
  26. }
  27. /**
  28. * Your MinStack object will be instantiated and called as such:
  29. * obj := Constructor();
  30. * obj.Push(x);
  31. * obj.Pop();
  32. * param_3 := obj.Top();
  33. * param_4 := obj.GetMin();
  34. */