2020-03-23
The minimum stack
Please a stack design, in addition to the conventional stack push and pop functions supported, also supports the min function, the function returns the minimum value of the stack elements. Performing push, pop operations and min time complexity must be O (1)
Example:
Mins Thanks mins thanks = new Mins Thanks ();
minStack.push (-2);
minStack.push (0);
minStack.push (-3);
minStack.getMin (); -> returns -3.
minStack.pop ();
minStack.top (); -> 0 is returned.
answer:
1 idea: Stack foundation
Basic Operation stack data format
/** * initialize your data structure here. */ var MinStack = function () { this.stack = []; this.index = 0; }; /** * @param {number} x * @return {void} */ MinStack.prototype.push = function (x) { this.stack[this.index++] = x; // 最后一项插入 }; /** * @return {void} */ MinStack.prototype.pop = function () { this= .stack.length the this .index -. 1; // by reducing the length deleting the last one the this .index-- ; }; / * * * @return {Number} * / MinStack.prototype.top = function () { // returns the last one return the this .stack [ the this .index -. 1 ]; }; / * * * @return {Number} * / MinStack.prototype.getMin = function () { // Get the minimum return Math.min (... the this .stack); }; / * * * Your MinStack object will be instantiated and called as such: * var obj = new MinStack() * obj.push(x) * obj.pop() * var param_3 = obj.top() * var param_4 = obj.getMin() */