155. Min Stack

Description:

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

My code:

/**
 * initialize your data structure here.
 */
var MinStack = function() {
    this.dataStore = [];
    this.length = 0;
};

/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
    this.dataStore[this.length++] = x;
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
    let temp = this.dataStore[this.length];
    this.length--;
    this.dataStore.length--;
    return temp;
};

/**
 * @return {number}
 */
MinStack.prototype.top = function() {
    return this.dataStore[this.length - 1];
};

/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
    let min = Number.MAX_VALUE;
    for(let i = 0; i <= this.length; i++) {
        if(min > this.dataStore[i]) {
            min = this.dataStore[i];
        }
    }
    return min;
};

/** 
 * Your MinStack object will be instantiated and called as such:
 * var obj = Object.create(MinStack).createNew()
 * obj.push(x)
 * obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.getMin()
 */

Note: 虽然是写出来了,但是Submissions那里看到run time是1000多…… 还需要优化,getMin可以舍弃for循环的

你可能感兴趣的:(155. Min Stack)