Share My 29ms Dynamic Array Code Here


  • 0
    M

    Using Basic C dynamic array without std::stack, since it would mean less if using stack to implement stack itself.

    class MinStack {
    public:
        /** initialize your data structure here. */
        MinStack() {
            stack = new int[N]; 
            minStack = new int[N];
        }
        
        void push(int x) {
            stack[L] = x;
            if(L > 0) minStack[L] = x < minStack[L-1] ? x : minStack[L-1];
            else minStack[L] = x;
            L++;
            
            if(L == N) {
               int* stackReloc = new int[N*2];
               int* minStackReloc = new int[N*2];
                
               memcpy(stackReloc, stack, L * sizeof(int));
               memcpy(minStackReloc, minStack, L * sizeof(int));
               
               delete [] stack;
               delete [] minStack;
               
               stack = stackReloc;
               minStack = minStackReloc;
                
               N = N * 2;
            }
        }
        
        void pop() {
            L--;
        }
        
        int top() {
            return stack[L-1];
        }
        
        int getMin() {
            return minStack[L-1];
        }
    private:
        int* stack;
        int* minStack;
        int N = 1000, L = 0;
    };
    
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(x);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.getMin();
     */
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.