版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27667379/article/details/81558557
第6题
题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
感觉就是一个变形的二分查找,上代码
public class Solution {
public int minNumberInRotateArray(int[] array) {
int low = 0, high = array.length - 1;
while (low < high) {
int mid = low + (high-low) / 2;
if (array[mid] > array[high]) {
low = mid + 1;
} else if (array[mid] == array[high]) {
high = high - 1;
} else {
high = mid;
}
}
return array[low];
}
}
第7题
题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
public int Fibonacci(int n) {
return Fibonacci(0,1,n);
}
public static int Fibonacci(int a1,int a2,int n){
if (n==0) return 0;
if (n==1) return a2;
else return Fibonacci(a2,a1+a2,n-1);
}
似乎就是一个递归题,就是要考虑到从0开始的问题。
第8题:
题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)
思路:找规律 f(1) = 1, f(2) = 2, f(3) = 3, f(4) = 5, 可以总结出f(n) = f(n-1) + f(n-2)
代码:
public class Solution {
public int JumpFloor(int target) {
if (target==1) return 1;
if (target==2) return 2;
else return JumpFloor(target-1)+JumpFloor(target-2);
}
}