Leetcode 155. Min Stack

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.

分析

实现一个简单的栈。但是要求常量时间内得到最小值,做题时候忽略了这个信息,C代码的实现如下,已通过。
如果需要常量时间得到最小值,数据结构中需要以空间换时间。加入数组依次保存某元素之前堆栈的最小值,只需要在push新值时候更新。或者加入一个值来保存堆栈目前的最小值,当push或pop时候需要更新该值。

typedef struct {
    long long *val;
    int num;
    int max;
} MinStack;

/** initialize your data structure here. */
MinStack* minStackCreate(int maxSize) {
    MinStack* ans=(MinStack*)malloc(sizeof(MinStack));
    ans->val=(long long *)malloc(sizeof(long long )*maxSize);
    ans->num=0;
    ans->max=maxSize;
    return ans;
}

void minStackPush(MinStack* obj, int x) {
    obj->val[obj->num]=x;
    obj->num=obj->num+1;
}

void minStackPop(MinStack* obj) {
    if(obj->num>0)
        obj->num=obj->num-1;
}

int minStackTop(MinStack* obj) {
    int ans=obj->val[obj->num-1];
    return ans;
}

int minStackGetMin(MinStack* obj) {
    if(obj->num==0)
        return 0;
    int ans=obj->val[0];
    for(int i=1;inum;i++)
    {
        if(ans>obj->val[i])
            ans=obj->val[i];
    }
    return ans;
}

void minStackFree(MinStack* obj) {
    free(obj->val);
    free(obj);
}

/**
 * Your MinStack struct will be instantiated and called as such:
 * struct MinStack* obj = minStackCreate(maxSize);
 * minStackPush(obj, x);
 * minStackPop(obj);
 * int param_3 = minStackTop(obj);
 * int param_4 = minStackGetMin(obj);
 * minStackFree(obj);
 */

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