Leetcode第155题 最小栈
    思路
    参考liweiwei1419的思路
    利用一个辅助栈,使得每个元素与其相应的最小值时刻保持一一对应。
    (1)辅助栈为空的时候,必须放入新进来的数;
    (2)新来的数小于或者等于辅助栈栈顶元素的时候,才放入,特别注意这里“等于”要考虑进去,因为出栈的时候,连续的、相等的并且是最小值的元素要同步出栈;
    (3)出栈的时候,辅助栈的栈顶元素等于数据栈的栈顶元素,才出栈。
    总结一下:出栈时,最小值出栈才同步;入栈时,最小值入栈才同步。

    1. /**
    2. * initialize your data structure here.
    3. */
    4. var MinStack = function() {
    5. this.stack=[]
    6. //辅助栈
    7. this.stack2=[]
    8. };
    9. /**
    10. * @param {number} val
    11. * @return {void}
    12. */
    13. MinStack.prototype.push = function(val) {
    14. this.stack.push(val)
    15. if(this.stack2.length == 0 || this.stack2[this.stack2.length-1]>=val){
    16. this.stack2.push(val)
    17. }
    18. };
    19. /**
    20. * @return {void}
    21. */
    22. MinStack.prototype.pop = function() {
    23. if(this.stack.pop()===this.stack2[this.stack2.length-1]){
    24. this.stack2.pop()
    25. }
    26. };
    27. /**
    28. * @return {number}
    29. */
    30. MinStack.prototype.top = function() {
    31. return this.stack[this.stack.length-1]
    32. };
    33. /**
    34. * @return {number}
    35. */
    36. MinStack.prototype.getMin = function() {
    37. return this.stack2[this.stack2.length-1]
    38. };
    39. /**
    40. * Your MinStack object will be instantiated and called as such:
    41. * var obj = new MinStack()
    42. * obj.push(val)
    43. * obj.pop()
    44. * var param_3 = obj.top()
    45. * var param_4 = obj.getMin()
    46. */