leetcode 155:Min Stack
2015-07-06 16:55
316 查看
题目:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
分析:
本题考察栈的操作,要求实现push,pop,top,getMin四个函数,对于push,pop,top可以直接调用java中Stack的相关方法;getMin()函数可以通过新设一个存储最小元素的栈来实现,意思就是创建两个栈,一个栈正常执行相关操作,另一个栈只存储当前最小栈元素。
代码:
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.
分析:
本题考察栈的操作,要求实现push,pop,top,getMin四个函数,对于push,pop,top可以直接调用java中Stack的相关方法;getMin()函数可以通过新设一个存储最小元素的栈来实现,意思就是创建两个栈,一个栈正常执行相关操作,另一个栈只存储当前最小栈元素。
代码:
import java.util.Stack; public class minStack { Stack<Integer> stack=new Stack<Integer>(); Stack<Integer> minStack=new Stack<Integer>(); public void push(int x) { if(minStack.isEmpty()|| x<minStack.peek()){ minStack.push(x); } stack.push(x); } public void pop() { if(minStack.peek().equals(stack.peek())) minStack.pop(); stack.pop(); } public int top() { int top=stack.peek(); return top; } public int getMin() { int min=minStack.peek(); return min; } public static void main(String[] args){ minStack ms=new minStack(); ms.push(-3); int x=ms.getMin(); System.out.println("min:"+x); } }
相关文章推荐
- HTTP协议之Cookie
- 【基于Android的ARM汇编语言系列】之四:ARM处理器的寻址方式
- Linux 简介
- TCP协议详解(理论篇)
- 斐波那契数列算法的优化设计
- leetcode Flatten Binary Tree to Linked List树
- 大型网站架构演化
- Xposed框架之函数Hook学习
- 【基于Android的ARM汇编语言系列】之三:ARM汇编语言程序结构
- 6.8 一般处理语言
- JavaScript的一些要点吧~偶然发现的
- lua学习总结
- C++ limits头文件的用法(numeric_limits)
- unity3d开源Ultimate MMORPG插件技术文档渣翻译第3页
- Android设计模式系列--原型模式
- HTML基础介绍一(基本构造head,body,字体,段落)
- leetCode 19.Remove Nth Node From End of List(删除倒数第n个节点) 解题思路和方法
- 从"分层二进制输出"至"解决二进制树深度"总结
- JavaScript中运算符的优先级
- 产品经理学习总结之技术和设计篇