题目描述:设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) —— 将元素 x 推入栈中。 pop() —— 删除栈顶的元素。 top() —— 获取栈顶元素。 getMin() —— 检索栈中的最小元素。

示例:

MinStack minStack = new MinStack();

minStack.push(-2);

minStack.push(0);

minStack.push(-3);

minStack.getMin(); —> 返回 -3.

minStack.pop();

minStack.top(); —> 返回 0.

minStack.getMin(); —> 返回 -2.

思路:初始化一个最小值变量,它的初始值可以设一个非常大的数(比如 Infinity),然后开始遍历整个栈。在遍历的过程中,如果遇到了更小的值,就把最小值变量更新为这个更小的值。这样遍历结束后,我们就能拿到栈中的最小值了。
这个过程中,我们对栈进行了一次遍历,时间复杂度无疑是 O(n)

  1. /**
  2. * 初始化你的栈结构
  3. */
  4. const MinStack = function() {
  5. this.stack = []
  6. };
  7. /**
  8. * @param {number} x
  9. * @return {void}
  10. */
  11. // 栈的入栈操作,其实就是数组的 push 方法
  12. MinStack.prototype.push = function(x) {
  13. this.stack.push(x)
  14. };
  15. /**
  16. * @return {void}
  17. */
  18. // 栈的入栈操作,其实就是数组的 pop 方法
  19. MinStack.prototype.pop = function() {
  20. this.stack.pop()
  21. };
  22. /**
  23. * @return {number}
  24. */
  25. // 取栈顶元素,咱们教过的哈,这里我本能地给它一个边界条件判断(其实不给也能通过,但是多做不错哈)
  26. MinStack.prototype.top = function() {
  27. if(!this.stack || !this.stack.length) {
  28. return
  29. }
  30. return this.stack[this.stack.length - 1]
  31. };
  32. /**
  33. * @return {number}
  34. */
  35. // 按照一次遍历的思路取最小值
  36. MinStack.prototype.getMin = function() {
  37. let minValue = Infinity
  38. const { stack } = this
  39. for(let i=0; i<stack.length;i++) {
  40. if(stack[i] < minValue) {
  41. minValue = stack[i]
  42. }
  43. }
  44. return minValue
  45. };

时间复杂度 0(n)

时间效率更高的做法

增加一个栈 stack2 作为辅助栈

  1. const MinStack = function() {
  2. this.stack = [];
  3. // 定义辅助栈
  4. this.stack2 = [];
  5. };
  6. /**
  7. * @param {number} x
  8. * @return {void}
  9. */
  10. MinStack.prototype.push = function(x) {
  11. this.stack.push(x);
  12. // 若入栈的值小于当前最小值,则推入辅助栈栈顶
  13. if(this.stack2.length == 0 || this.stack2[this.stack2.length-1] >= x){
  14. this.stack2.push(x);
  15. }
  16. };
  17. /**
  18. * @return {void}
  19. */
  20. MinStack.prototype.pop = function() {
  21. // 若出栈的值和当前最小值相等,那么辅助栈也要对栈顶元素进行出栈,确保最小值的有效性
  22. if(this.stack.pop() == this.stack2[this.stack2.length-1]){
  23. this.stack2.pop();
  24. }
  25. };
  26. /**
  27. * @return {number}
  28. */
  29. MinStack.prototype.top = function() {
  30. return this.stack[this.stack.length-1];
  31. };
  32. /**
  33. * @return {number}
  34. */
  35. MinStack.prototype.getMin = function() {
  36. // 辅助栈的栈顶,存的就是目标中的最小值
  37. return this.stack2[this.stack2.length-1];
  38. };

时间复杂度 0(1)