剑指 Offer 30. 包含min函数的栈(简单)

通过率 57.7%

题目链接

题目描述:

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.

提示:

各函数的调用总次数不超过 20000 次

思路:

本题的重点在于将min方法的时间复杂度降为 O(1)(push 及 pop的时间复杂度本就是O(1))

stackA维护原数组,stackB维护当前状态下栈A中的最小值

  • push入栈时,判断栈B是否为空或者x是否小于等于B栈顶的值,若是,则将x压入栈B
  • pop出栈时,判断A栈顶的值是否等于B栈顶的值,若是,说明A的最小值将出栈,则也将B栈顶的值出栈
  • min求最小值时,返回B栈顶的值即可
 1 /*JavaScript*/
 2 /**
 3  * initialize your data structure here.
 4  */
 5 var MinStack = function() {
 6     MinStack.prototype.stackA = []
 7     MinStack.prototype.stackB = []
 8 };
 9 
10 /** 
11  * @param {number} x
12  * @return {void}
13  */
14 MinStack.prototype.push = function(x) {
15     this.stackA.push(x)
16     if(!this.stackB.length || x <= this.stackB[this.stackB.length-1]) this.stackB.push(x)
17 };
18 
19 /**
20  * @return {void}
21  */
22 MinStack.prototype.pop = function() {
23     if(this.stackA.pop() === this.stackB[this.stackB.length-1]) this.stackB.pop()
24 };
25 
26 /**
27  * @return {number}
28  */
29 MinStack.prototype.top = function() {
30     if(this.stackA.length) return this.stackA[this.stackA.length-1]
31 };
32 
33 /**
34  * @return {number}
35  */
36 MinStack.prototype.min = function() {
37     if(this.stackB.length) return this.stackB[this.stackB.length-1]
38 };
39 
40 /**
41  * Your MinStack object will be instantiated and called as such:
42  * var obj = new MinStack()
43  * obj.push(x)
44  * obj.pop()
45  * var param_3 = obj.top()
46  * var param_4 = obj.min()
47  */

 

posted @ 2021-08-07 18:41  自在逍遥处  阅读(26)  评论(0编辑  收藏  举报