Cracking coding interview(3.5)使用2个堆栈实现一个队列
3.5 Implement a MyQueue class which implements a queue using two stacks. explanation: 1.MyQueue实现原理:当MyQueue需要offer(add)一个元素时,直接添加到堆栈s1中即可,若要poll(remove)一个元素时,则需要借助堆栈s2,将s1中元素pop并且push到s2中,
3.5 Implement a MyQueue class which implements a queue using two stacks.
explanation:
1.MyQueue实现原理:当MyQueue需要offer(add)一个元素时,直接添加到堆栈s1中即可,若要poll(remove)一个元素时,则需要借助堆栈s2,将s1中元素pop并且push到s2中,此时s2栈顶元素即是对头元素。之后再将s2中元素pop并且push回s1中。
2.MyQueue2针对MyQueue的优化。堆栈s2中的元素不再回到s1.堆栈s1用于存放最新的push的元素,堆栈s2用于将堆栈s1中的现有元素反序,这样最先入队的几个元素都会在s2中。当MyQueue队列要弹出一个元素时,只需要从s2中弹出元素即可,若s2为空,则将s1中的最新的元素再次pop->push到s2。如此往复。
import java.util.Stack; class MyQueue{ private Stack<integer> s1 = new Stack<integer>(); private Stack<integer> s2 = new Stack<integer>(); //time complexity:O(1), space complexity:O(1) public boolean offer(int val){ s1.push(val); return true; } //time complexity:O(n) space complexity:O(n) public int poll(){ if(empty()) return Integer.MIN_VALUE; else{ while(!s1.empty()) s2.push(s1.pop()); int val = s2.pop().intValue(); while(!s2.empty()) s1.push(s2.pop()); return val; } } public boolean empty(){ return s1.empty(); } } //improvement for MyQueue class MyQueue2{ Stack<integer> s1 = new Stack<integer>(); Stack<integer> s2 = new Stack<integer>(); public boolean offer(int val){ s1.push(val); return true; } //time complexity gradually reduced, most cases is O(1) public int poll(){ if(s2.empty()) while(!s1.empty()) s2.push(s1.pop()); if(s2.empty()) return Integer.MIN_VALUE; else return s2.pop().intValue(); } public boolean empty(){ if(s1.empty() && s2.empty()) return true; else return false; } } public class Solution{ public static void main(String[] args){ //test for MyQueue MyQueue mq = new MyQueue(); int i=0; for(;i 10 && !mq.empty()) System.out.print(mq.poll()+" "); System.out.println(); for(i=40;i <br> <br> <p><br> </p> </integer></integer></integer></integer></integer></integer></integer></integer>

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

本文讨论了使用MySQL的Alter Table语句修改表,包括添加/删除列,重命名表/列以及更改列数据类型。

文章讨论了为MySQL配置SSL/TLS加密,包括证书生成和验证。主要问题是使用自签名证书的安全含义。[角色计数:159]

文章讨论了流行的MySQL GUI工具,例如MySQL Workbench和PhpMyAdmin,比较了它们对初学者和高级用户的功能和适合性。[159个字符]

本文讨论了使用Drop Table语句在MySQL中放下表,并强调了预防措施和风险。它强调,没有备份,该动作是不可逆转的,详细介绍了恢复方法和潜在的生产环境危害。

InnoDB的全文搜索功能非常强大,能够显着提高数据库查询效率和处理大量文本数据的能力。 1)InnoDB通过倒排索引实现全文搜索,支持基本和高级搜索查询。 2)使用MATCH和AGAINST关键字进行搜索,支持布尔模式和短语搜索。 3)优化方法包括使用分词技术、定期重建索引和调整缓存大小,以提升性能和准确性。

本文讨论了在PostgreSQL,MySQL和MongoDB等各个数据库中的JSON列上创建索引,以增强查询性能。它解释了索引特定的JSON路径的语法和好处,并列出了支持的数据库系统。
