用两个栈实现队列
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路
栈的特性:先进后出;队的特性:先进先出。两个栈实现一个队列,一个栈作为输入数据的输入栈,一个栈作为输出的输出栈。
- 队列的输入—
push
:可以很容易的理解输入栈的push
就可以实现 - 队列的输出—
pop
:输出栈为空时,输入栈数据压入输出栈,再由输出栈输出可以实现队列的先入先出特性。
注:
- 输入栈压入数据到输出栈时,必须一次性全部将数据给输出栈
- 输入栈压入数据到输出栈时,输出栈必须为空
代码
import java.util.Stack;
/**
* 剑指offer一刷:用两个栈实现队列
*
* @author User
* @create 2019-05-12-13:50
*/
public class jzo05 {
Stack<Integer> stack1=new Stack<>();
Stack<Integer> stack2=new Stack<>();
public void push(int node){ //stack1入栈
stack1.push(node);
}
public int pop(){ //stack2出栈
if(stack2.isEmpty()){
while (!stack1.isEmpty()){
int node=stack1.pop();
stack2.push(node);
}
}
return stack2.pop();
}
public static void main(String[] args){
jzo05 queue=new jzo05();
queue.push(1);
queue.push(2);
queue.push(3);
queue.push(4);
queue.push(5);
queue.push(6);
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
}
}
旋转数组的最小数字
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
解题思路
从后往前遍历数组,当array[i]<array[i-1]时,第i个数组就是旋转数组的最小值。本题多加了旋转数组的排序重组,通过System.arraycopy()
方法合并两个数组。
System.arraycopy()
的源码
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
代码
/**
* 剑指offer一刷:旋转数组的最小数字
*
* @author User
* @create 2019-05-12-14:36
*/
public class jzo06 {
public int minNumberInRotateArray(int [] array) {
if(array.length==0){
return 0;
}
if(array.length==1){
return array[0];
}
int l=0; //标记递增子序列长度
int index=0;
for (int i=array.length-1;i>0;i--){
if(array[i]<array[i-1]){
index=i;
}
}
l=array.length-index;
int[] newArray=new int[array.length];
System.arraycopy(array,index,newArray,0,l);
System.arraycopy(array,0,newArray,l,index);
return newArray[0];
}
public static void main(String[] args){
int[] array=new int[]{3,4,5,1,2};
jzo06 so=new jzo06();
int num=so.minNumberInRotateArray(array);
System.out.println(num);
}
}