Runtime error ? Can't figure out problem.


  • 0
    N
    class MinStack {
        
        vector<int> stack;
        int min, minIdx;
        
    public:
        void push(int x) {
            
            if(stack.size()==0) 
            {
                min=x;
                minIdx=0;
            }
            else 
            {
                if(min>x)
                {
                    stack.push_back(minIdx);
                    min=x;
                    minIdx=stack.size()+1;
                }
            }
            
            stack.push_back(x);
        }
    
        void pop() {
            
            if(stack.size()==0) return;
            
            int t = top();
            
            if(min==t && minIdx==stack.size()-1)
            {
                stack.pop_back();
                minIdx = top();
                if(minIdx<stack.size())
                    min = stack[minIdx];
            }
            
            stack.pop_back();
        }
    
        int top() {
            return stack.back();
        }
    
        int getMin() {
            return min;
        }
    };

  • 1
    R

    Same here, No idea what's wrong. It works fine on my eclipse.

    class MinStack {
    ArrayList<Integer> stack = new ArrayList<Integer>();
    ArrayList<Integer> minstack = new ArrayList<Integer>();
    int size = 0;
    
    void push(int x)
    {
        if(stack.isEmpty())
        {
            minstack.add(x);
            stack.add(x);
        }
        else
        {
        	stack.add(x);
            int oldmin = minstack.get(size-1);
            if(x < oldmin) minstack.add(x);
            else minstack.add(oldmin);
        }
        size ++;
    }
    
    void pop()
    {
        stack.remove(size-1);
        minstack.remove(size-1);
    }
    
    int top()
    {
        return stack.get(size-1);
    }
    
    int getMin()
    {
        return minstack.get(size-1);
    }
    

    }


  • 0
    E

    Pay attention to the pop() function.

    if(min==t && minIdx==stack.size()-1)
    

    if minIdx == 0 will result in empty vector after stack.pop_back() inside the if block.


Log in to reply
 

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