Cracking the coding interview--Q3.5

Google面试之快乐智力题(Cracking the Coding Interview) 问:有20瓶药,其中19瓶装的都是1.0克的药片,只有1瓶装了1.1克的药。给你一个能称出具体克数的电子秤,只允许你称一次,怎么找出那瓶不一样的? 答:如果药片足够,从第i(1<i<20)个瓶子里取出数量为i的药片称重为Xg,[X-(21*20/2)]/0.1即为装了1.1g药的瓶子的编号。 Q:A bunch of men are on an island. A genie ... 阅读详情

原文:

Implement a MyQueue class which implements a queue using two stacks.

译文:

使用两个栈实现一个队列MyQueue。


队列是先进先出的数据结构(FIFO),栈是先进后出的数据结构(FILO), 用两个栈来实现队列的最简单方式是:进入队列则往第一个栈压栈, 出队列则将第一个栈的数据依次压入第二个栈,然后出栈。此时第二个栈顶元素即为队头元素,然后可以把队2元素再次押回栈1.

package chapter_3_StacksandQueues;

import java.util.Scanner;

class Stack_3_5 {
	private int top;
	private int size;
	private int[] data;
	
	public Stack_3_5(int size) {
		this.size = size;
		this.top = -1;
		this.data = new int[size];
	}
	
	public boolean isEmpty() {
		return top < 0;
	}
	
	public boolean isFull() {
		return top == (size-1);
	}
	
	public void push(int value) {
		if(isFull()) {
			System.out.println("Stack is full!");
			return;
		}
		data[++top] = value;
	}
	
	public void pop() {
		if(isEmpty()) {
			System.out.println("Stack is empty!");
			return;
		}
		
		top --;
	}
	
	public int top() {
		if(isEmpty()) {
			System.out.println("Stack is empty!");
			return -1;
		}
		return data[top];
	}
}

class MyQueue {
	private Stack_3_5 stack1, stack2;
	private int size;
	
	public MyQueue(int size) {
		stack1 = new Stack_3_5(size);
		stack2 = new Stack_3_5(size);
		this.size = 0;
	}
	
	// 入队,则直接在数据元素栈入栈元素即可
	public void inQueue(int value) {
		if(stack1.isFull()) {
			System.out.println("MyQueue is full!");
			return;
		}
		stack1.push(value);
		size ++;
	}
	
	// 元素出队,则需要把数据元素栈内元素依次出栈存入另一个栈内,
	// 借助另一个栈获取队头元素
	public int deQueue() {
		if(stack1.isEmpty()) {
			System.out.println("MyQueue is empty!");
			return -1;
		}
		
		while(!stack1.isEmpty()) {
			int value = stack1.top();
			stack1.pop();
			stack2.push(value);
		}
		int result = stack2.top();
		stack2.pop();
		size --;
		while(!stack2.isEmpty()) {
			int value = stack2.top();
			stack2.pop();
			stack1.push(value);
		}
		return result;
	}
}

/**
 *
 * 使用两个栈实现一个队列MyQueue
 *
 */
public class Question_3_5 {
	public static void main(String args[]) {
		Scanner scanner = new Scanner(System.in);
		int testNum = scanner.nextInt();
		scanner.nextLine();
		while(testNum -- > 0) {
			MyQueue queue = new MyQueue(5);
			
			String str = scanner.nextLine();
			String strs[] = str.split(" ");
			
			for(int i=0; i< 6; i++) {
				queue.inQueue(Integer.parseInt(strs[i]));
			}
			
			for(int i=0; i<3; i++) {
				int data = queue.deQueue();
				if(data != -1) {
					System.out.println("出队元素: " + data);
				}	
			}
			
			for(int i=6; i< strs.length; i++) {
				queue.inQueue(Integer.parseInt(strs[i]));
			}
		}
	}
}


上面的方法则每次获取队首元素都需要翻转整一个栈1,使得效率很低。

可以使用如下方法:

元素入队,则直接压入栈1,不用管栈2,如果元素出对,则首先判断栈2是否为空,如果为空,则栈1元素一次入栈压入栈2.,如果栈2不为空,则此时

获取栈2栈顶元素,因为此时栈2栈顶元素即为队首元素。这样没入入队和出对效率就增高,并且如果出对入队频繁,则队列的长度存储空间也会增加,

栈1和栈2加起来即为队列的长度,对首到中间的数据在栈2 中存储, 中间到对尾数据存储在栈1中。

package chapter_3_StacksandQueues;

import java.util.Scanner;

class MyQueue_3_5_2 {
	private Stack_3_5 stack1, stack2;
	private int size;
	
	public MyQueue_3_5_2(int size) {
		stack1 = new Stack_3_5(size);
		stack2 = new Stack_3_5(size);
		this.size = 0;
	}
	
	public boolean isEmpty() {
		return size == 0;
	}
	
	// 入队,则直接在数据元素栈入栈元素即可
	public void inQueue(int value) {
		if(stack1.isFull()) {
			System.out.println("MyQueue is full!");
			return;
		}
		stack1.push(value);
		size ++;
	}
	
	// 出栈则先获取第二个栈内数据,为空则第一个栈全部出栈并入栈第二个栈
	// 获取第二个栈顶元素,此时第二个栈顶元素就是队首元素
	public int deQueue() {
		if(size == 0) {
			System.out.println("MyQueue is empty!");
			return -1;
		}
		
		if(stack2.isEmpty()) {
			while(!stack1.isEmpty()) {
				int value = stack1.top();
				stack1.pop();
				stack2.push(value);
			}
		} 
		
		int result = stack2.top();
		stack2.pop();
		size --;
		return result;
	}
}

/**
*
* 使用两个栈实现一个队列MyQueue
*
*/
public class Question_3_5_2 {
	public static void main(String args[]) {
		Scanner scanner = new Scanner(System.in);
		int testNum = scanner.nextInt();
		scanner.nextLine();
		while(testNum -- > 0) {
			MyQueue_3_5_2 queue = new MyQueue_3_5_2(5);
			
			String str = scanner.nextLine();
			String strs[] = str.split(" ");
			
			for(int i=0; i< 6; i++) {
				queue.inQueue(Integer.parseInt(strs[i]));
			}
			
			for(int i=0; i<3; i++) {
				int data = queue.deQueue();
				if(data != -1) {
					System.out.println("出队元素: " + data);
				}	
			}
			
			for(int i=5; i< strs.length; i++) {
				queue.inQueue(Integer.parseInt(strs[i]));
			}
			
			while(!queue.isEmpty()) {
				System.out.println("出队元素: " + queue.deQueue());
			}
		}
	}
}



VS2022离线安装包 - 下载安装教程 阅读详情

相关推荐

计算机技术发展5大阶段,现阶段计算机技术应用及发展

【摘要】现代计算机科学技术的发展和普及运用,为世界各国民众基础性生产生活实践活动的组织开展路径造成了深刻影响,本文围绕现阶段计算机技术应用及发展,择取两个具体方面,展开了简要分析。【关键词】计算机技术;应用;发展改革开放以来,计算机设备的广泛运用,促进了计算机科学技术的逐步发展成熟。计算机科学技术是具备新兴表现特征的尖端应用技术,其在现代工业生产和社会生活实践活动过程中的广泛引入运用,给世界各国基...

weixin_42126677的博客 2637

Cracking the coding interview--Q5.3

题目 原文: Given an integer, print the next smallest and next largest number that have the same number of 1 bits in their binary representation. 译文: 给一个整数,打印两个数,并且他们的二进制表示中的1的个数和这个整数的一样,其中一个是比该数大的数中

cfanr 1500

SAR成像系列:【3】合成孔径雷达(SAR)的二维回波信号与简单距离多普勒(RD)算法 (附matlab代码)

二维回波信号分析

zr2006_7的专栏 2万+

Cracking the coding interview--Q4

Chapter 4 | Trees and Graphs 4.1 Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ

763

MagicDraw-需求图

MagicDraw学习笔记

木头征的博客 4134

Redis+Unity 数据库搭建

游戏中需要存放排行榜等数据,而且是实时存放,所以就涉及到数据库的问题。这里找服务器大神了解到可以用Redis来做存储,免费的效率极高。

chaixinke的专栏 878

cracking-the-coding-interview的核心秘密:如何用单元测试“定义”面试题?C++ Catch+Python unittest的TDD完整教程

cracking-the-coding-interview 是一个为《Cracking the Coding Interview》(CTCI)第 6 版提供 **C++ 与 Python 双语言解法** 的开源项目,其最大特色是:**每一道面试题的解法都配有完整的自动化单元测试**(C++ 端用 Catch 框架,Python 端用 unittest 框架),自动化测试覆盖率超过 90%。更妙的是

gitblog_00501的博客 317

软考 系统架构设计师历年真题集萃(248)

软考 系统架构设计师历年真题集萃(248)

phmatthaus的专栏 789

Cracking the coding interview--Q9

Chapter 9 | Sorting and Searching 9.1 You are given two sorted arrays, A and B, and A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order. 插入排序,需要调整数

1020

SAP-ABAP:SAP的BAPI_GOODSMVT_CREATE 深度解析

BAPI_GOODSMVT_CREATE 深度解析** **功能定位**:SAP 标准接口,支持 **11 种库存移动场景**(收货/发货/转储/生产投料等),是 MM 模块集成核心

baidu_35680696的博客 1823

SAR图像去斑(Despeckling)研究的主流开源数据集

这些数据集专门用于训练监督学习去斑模型,提供了配对的含斑SAR图像和对应的无噪声参考图像(Ground Truth)。这些数据集主要用于目标检测/识别,但包含原始SAR图像,可用于。由于缺乏真实无噪声SAR图像,许多研究采用。

VectorShift的博客 128

Cracking the coding interview--Q17

Chapter 17 | Networking 17.1 Explain what happens, step by step, after you type a URL into a browser. Use as much detail as possible.  先进行DNS的namequery,得到对方的cname或者a记录(当然也可能是IPV6),反正就最后得到对方的IP

630

工作之余的随想:AI 会终结 SAP 顾问吗?

本文是笔者工作之余的一些胡思乱想。昨晚(准确的说是今日凌晨),我又熬了一个夜。没办法,接到一个影响客户项目上线的紧急 incident,花了我好长时间,竟然一点头绪都没有。苦苦思索的过程,时间过得飞快。一转眼就晚上11:30 了。要说我 2007 年还在研三实习期间,就进入了 SAP 行业,到今天已经摸爬滚打 18 年了,按理说也算身经百战了,可以说处理过很多 SAP 客户使用系统时遇到的各种稀奇古怪的问题。但即便这样,我也时常在工作中遇到一开始感到无从下手的问题。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1262

Cracking the coding interview--Q3.6

原文: Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write thi

执子之手 560

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

渣基础:比照Hawstein学Cracking the coding interview(1)

《C++ Primer 第五版》书实在是太长,太厚了。总是看了十几页就看累了,坚持不了多久,想了想还是别勉强自己,jued

低端玩家的记录地 949

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

Cracking the coding interview--Q9.3

题目 原文: Given a sorted array of n integers that has been rotated an unknown number of times, give an O(log n) algorithm that finds an element in the array. You may assume that the array was originall

cfanr 1620

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

Cracking the coding interview--Q12.5

题目 原文: If you were designing a web crawler, how would you avoid getting into infinite loops? 译文: 如果你正在设计一个网络爬虫,何如避免进入无限循环? 解答

cfanr 1630

Cracking the coding interview--Q2.5

Cracking the coding interview--Q2.5 December 17, 2012 作者:Hawstein 出处:http://hawstein.com/posts/2.5.html 声明:本文采用以下协议进行授权: 自由转载-非商用-非衍生-保持署名|Creative Commons BY-NC-ND 3.0 ,转载请注明作者及出处。 题目

pi9nc的专栏 817

Cracking the coding interview--Q19.3

题目 原文:

cfanr 1195

Cracking the coding interview--Q5.7

题目 原文: An array A[1... n] contains all the integers from 0 to n except for one number which is missing. In this problem, we cannot access an entire integer in A with a single operation. The elements

cfanr 1649

Cracking the coding interview--Q20.3

题目 原文: Write a method to randomly generate a set of m integers from an array of size n. Each element must have equal probability of being chosen. 译文:

cfanr 1296

Cracking the coding interview--Q1.5

Cracking the coding interview--Q1.5 原文 Implement a method to perform basic string compression using the countsof repeated characters. For example, the string aabcccccaaa w...

weixin_34378045的博客 115

Cracking the coding interview--Q5

Chapter 5 | Bit Manipulation 5.1 You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a subst

951

Cracking the coding interview--Q2.3

Cracking the coding interview--Q2.3 Implement an algorithm to delete a node in the middle of a singly linked list,given only access to that node.EXAMPLEInput: the node c fro...

weixin_34138139的博客 101
上一篇: Cracking the coding interview--Q3.4
下一篇: Cracking the coding interview--Q3.6
java_wliang
博客等级 码龄15年 19粉丝 82原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值