leetcode求栈中最小的元素

来源:互联网 发布:数据分析是做什么的 编辑:程序博客网 时间:2024/05/21 05:43
55. Min Stack   QuestionEditorial Solution  My Submissions

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.

题目的大概意思就是设计一个栈,然后里面可以获得最小的元素,这段代码里面有几个是需要注意的,一个是栈的大小,最小的元素,最小的元素的大小,如何求最小的元素,和求最小的元素的个数,代码:

class MinStack {private:   long min=2147483648;   int min_count=1;   int *stack;   int stack_max_count=10000;   int index=-1;public:    /** initialize your data structure here. */    MinStack() {        stack=(int *)malloc(sizeof(int)*stack_max_count);    }        void push(int x) {        if(x<min) min=x;        else if(x==min) min_count++;        if(stack_max_count==index){            stack_max_count<<=1;            stack=(int*)realloc(stack,sizeof(int)*stack_max_count);        }        stack[++index]=x;    }        static int comp(const void* a,const void *b){        return *(int*)a-*(int*)b;    }    void pop() {        int poped=stack[index--];        if(index==-1){            min_count=1;            min=2147483648;            return ;        }{            if(poped==min)                if(min_count>1) min_count--;                else if(min_count==1){                    int *tmp_sort=(int*)malloc(sizeof(int)*(index+1));                    for(int i=0;i<=index;++i){                        tmp_sort[i]=stack[i];                    }                    qsort(tmp_sort,index+1,sizeof(int),comp);                    min=tmp_sort[0];                    for(int j=1;j<=index;j++){                        if(tmp_sort[j]==min) min_count++;                        else break;                    }                }            }        }    int top() {        return stack[index];    }        int getMin() {        return min;    }};/** * 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(); */


0 0