12ms C solution sharing


  • 0
    C
    typedef struct {
        int *arr;
        int maxSize;
        int top;
        int min;
    } MinStack;
    
    void minStackCreate(MinStack *stack, int maxSize) {
    
        stack->arr = (int*)malloc(sizeof(int)*maxSize);
        stack->maxSize = maxSize;
        stack->top = -1;
        stack->min = INT_MAX;
    }
    
    void minStackPush(MinStack *stack, int element) {
        
        if (stack->top < stack->maxSize-1)
        {
            if (element < stack->min)
            {
                stack->min = element;
            }
            
            stack->arr[++stack->top] = element;
        }
        else
        {
            // stack overflow
        }
    }
    
    void minStackPop(MinStack *stack) {
        int popVal;
        
        if (stack->top < 0)
        {
            return;
        }
        
        if (stack->top == 0)
        {
            stack->top--;
            stack->min = INT_MAX;
            return;
        }
        
        if (stack->top >= 0 && stack->top < stack->maxSize)
        {
            popVal = stack->arr[stack->top];
        }
        
        if (popVal == stack->min)
        {
            int i;
            int newMin = stack->arr[0];
            
            for (i=1; i<stack->top; i++)
            {
                if (stack->arr[i] < newMin)
                {
                    newMin = stack->arr[i];
                }
            }
            stack->min = newMin;
        }
        
        stack->top--;
    }
    
    int minStackTop(MinStack *stack) {
        
        if (stack->top >= 0 && stack->top < stack->maxSize)
        {
            return stack->arr[stack->top];
        }
    }
    
    int minStackGetMin(MinStack *stack) {
        return stack->min;
    }
    
    void minStackDestroy(MinStack *stack) {
        if (stack->arr)
            free(stack->arr);
    }

Log in to reply
 

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