5.用兩個棧實(shí)現(xiàn)隊(duì)列
用兩個棧來實(shí)現(xiàn)一個隊(duì)列,完成隊(duì)列的Push和Pop操作。 隊(duì)列中的元素為int類型。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int res =stack2.pop();
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return res;
}
}
6.旋轉(zhuǎn)數(shù)組的最小數(shù)字
把一個數(shù)組最開始的若干個元素搬到數(shù)組的末尾,我們稱之為數(shù)組的旋轉(zhuǎn)。輸入一個遞增排序的數(shù)組的一個旋轉(zhuǎn),輸出旋轉(zhuǎn)數(shù)組的最小元素。例如數(shù)組{3,4,5,1,2}為{1,2,3,4,5}的一個旋轉(zhuǎn),該數(shù)組的最小值為1。NOTE:給出的所有元素都大于0,若數(shù)組大小為0,請返回0。
#這題目解法還有問題
import java.util.ArrayList;
public class Solution {
public int minNumberInRotateArray(int [] array) {
if(array.length==0){
return 0;
}
int len = array.length;
int limit = array[0];
int start =0;
int end = len-1;
if(array[end] > limit ){
return limit;
}
/*
* 因?yàn)橛锌赡?,3,2,3的時候,最后只剩3,2的時候
* 最后可能一直在start= middle中出不來。所以限定條件是end-start>1
*/
while(end - start > 1){
int middle = (start+end)/2;
if(array[middle] > limit){
start= middle+1;
}else if(array[middle] < limit){
end = middle;
}else{
start= middle;
}
}
return array[start]<array[end] ? array[start]:array[end] ;
}
}
7.斐波那契數(shù)列
大家都知道斐波那契數(shù)列,現(xiàn)在要求輸入一個整數(shù)n,請你輸出斐波那契數(shù)列的第n項(xiàng)。
public class Solution {
public int Fibonacci(int n) {
if(n==0){
return 0;
}
if(n==2){
return 1;
}
if(n==1){
return 1;
}else{
return Fibonacci(n-1)+ Fibonacci(n-2);
}
}
}
8.跳臺階
一只青蛙一次可以跳上1級臺階,也可以跳上2級。求該青蛙跳上一個n級的臺階總共有多少種跳法。
public class Solution {
public int JumpFloor(int target) {
if(target==0){
return 0;
}
if(target==1){
return 1;
}
if(target==2){
return 2;
}else{
return JumpFloor(target-2)+JumpFloor(target-1);
}
}
}
public class Solution {
public int JumpFloor(int target) {
if(target==0){
return 0;
}
if(target==1){
return 1;
}
if(target==2){
return 2;
}else{
int a=1;int b= 2;
int i=3;
int sum = 0;
while(i<=target){
sum = a+b;
a=b;
b=sum;
i++;
}
return sum;
}
}
}
9.變態(tài)跳臺階
一只青蛙一次可以跳上1級臺階,也可以跳上2級……它也可以跳上n級。求該青蛙跳上一個n級的臺階總共有多少種跳法。
public class Solution {
public int JumpFloorII(int target) {
if(target==1){
return 1;
}else if(target==2){
return 2;
}
int sum=1;
for(int i=1;i<target;i++){
sum +=JumpFloorII(target-i);
}
return sum;
}
}
10.矩形覆蓋
我們可以用21的小矩形橫著或者豎著去覆蓋更大的矩形。請問用n個21的小矩形無重疊地覆蓋一個2*n的大矩形,總共有多少種方法?
public class Solution {
public int RectCover(int target) {
if(target==0){
return 0;
}
if(target==1){
return 1;
}else if(target==2){
return 2;
}else{
return RectCover(target-1)+RectCover(target-2);
}
}
}