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.
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
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.
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
- leetcode求栈中最小的元素
- [leetcode]Min Stack (获取栈的最小元素C语言实现)
- 旋转数组的最小元素
- 最小的k个元素
- 旋转数组的最小元素
- 旋转数组的最小元素
- 旋转数组的最小元素
- 旋转数组的最小元素
- 求栈的最小元素
- 旋转数组的最小元素
- 包含最小元素的栈
- 旋转数组的最小元素
- 得到栈的最小元素
- 删除链表中最小的元素
- 旋转数组的最小元素
- 旋转数组的最小元素
- 包含最小元素的栈
- 旋转数组的最小元素
- codevs1743 反转卡片
- Java终止某个线程的方法
- 19.BOM&DOM-动态操作节点
- 让sublime一行显示更多代码出现横向的滚动条,以及修改默认tab键长度
- 计算机网络之面试常考题
- leetcode求栈中最小的元素
- Android 热修复插件之AndFix
- spring mvc拦截器和<mvc:annotation-driven />的详解
- 数据结构实验之串一:KMP简单应用(java实现)
- BZOJ 2120 数颜色
- 理解String的compareTo()方法返回值
- Spring MVC静态资源处理
- 为什么判断 std::vector 是否为空时,用 if(0==vec.size()) 提示效率低,但用 if (vec.empty()) 正常?
- Android四大基本组件介绍与生命周期