6、旋转数组的最小数字
题目描述:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
解题思路:循环比较相邻两个元素的大小直至a[i+1] < a[i]即可
import java.util.ArrayList;
public class Solution {
public int minNumberInRotateArray(int [] array) {
if(array == null || array.length == 0) {
return 0;
}
for(int i = 0; i < array.length - 1; i++) {
if(array[i] > array[i+1]) {
return array[i+1];
}
}
return 0;
}
}
7、斐波那契数列
题目描述:大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
解题思路:n = 0, 1的情况直接返回,用循环和中间变量解决
public class Solution {
public int Fibonacci(int n) {
int a = 0;
int b = 1;
if(n == 0) {
return a;
}else if(n == 1) {
return b;
}else {
for(int i = 2; i <= n; i++) {
int temp = b;
b = a + b;
a = temp;
}
return b;
}
}
}
8、跳台阶
题目描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
解题思路:一只青蛙最后一次跳要么跳了1级,要么跳了2级,跳1级的跳法等于跳了n-1级的跳法, 跳了2级的等于跳了n-2级的跳法,f(n) = f(n-1)+f(n-2)
public class Solution {
public int JumpFloor(int target) {
if(target == 1) {
return 1;
}else if(target == 2) {
return 2;
}else{
return JumpFloor(target-1) + JumpFloor(target-2);
}
}
}
9、变态跳台阶
题目描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
解题思路:列出两个式子可知:
f(n) = f(n-1) + f(n-2) + f(n-3) + …… + f(1)
f(n-1) = f(n-2) + f(n-3) + …… + f(1)
可知f(n) = 2 f(n-1)
public class Solution {
public int JumpFloorII(int target) {
if(target == 1){
return 1;
}else {
return 2 * JumpFloorII(target - 1);
}
}
}
10、矩形覆盖
题目描述:我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
解题思路:类似上题,注意为0的情况
public class Solution {
public int RectCover(int target) {
if(target == 0) {
return 0;
}
else if(target == 1) {
return 1;
}else if(target == 2) {
return 2;
}else {
return RectCover(target-1) + RectCover(target-2);
}
}
}