leetcode--Min Stack
来源:互联网 发布:php json数组 编辑:程序博客网 时间:2024/06/05 15:21
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.
解:
用stack存储当前值和当前最小值的gap,这样就可以根据stack值是否大于0来判断当前min值是当前值还是之前的min值
public class MinStack { long min; Stack<Long> stack; public MinStack(){ stack=new Stack<>(); } public void push(int x) { if (stack.isEmpty()){ stack.push(0L); min=x; }else{ stack.push(x-min) if (x<min) min=x; } } public void pop() { if (stack.isEmpty()) return; long pop=stack.pop(); if (pop<0) min=min-pop; } public int top() { long top=stack.peek(); if (top>0){ return (int)(top+min); }else{ return (int)(min); } } public int getMin() { return (int)min; }}
0 0
- LeetCode[stack]: Min Stack
- [leetcode][stack] Min Stack
- 【Leetcode】Min Stack
- Leetcode: Min Stack
- leetcode Min stack
- Min Stack -- LeetCode
- Leetcode: Min Stack
- 【LeetCode】Min Stack
- leetcode Min Stack
- leetcode--Min Stack
- [Leetcode]Min stack
- leetcode:Min Stack
- leetcode 之 Min Stack
- leetcode Min Stack
- LeetCode(155) Min Stack
- [LeetCode]Min Stack
- leetcode:Min Stack
- leetcode - Min Stack
- 给未来的自己
- poj2559单调栈
- 把二叉树打印成多行
- 写给自己
- Python 学习之集合
- leetcode--Min Stack
- cf#186-C. Mr. Kitayuta, the Treasure Hunter-dp(预推断+offset)
- Rectangle Area-带有交差集矩形面积
- 单链表的反转
- regex_iterator()的使用sregex_iterator(),cregex_iterator()
- 多线程 线程的创建方式和多线程共享资源
- C小项目——电子词典
- 位运算符基础
- 挑战密室(化学方程式)