把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
note:给出的所有元素都大于0,若数组大小为0,请返回0。
解题思路:分治递归,直到出现一个递增的序列后停止。
import java.util.*; public class solution { public int minnumberinrotatearray(int [] array) { if(array.length==0) return 0; if(array[0] < array[array.length-1]||array.length==1) return array[0]; if(array.length==2) return array[1]; if(array[array.length/2]>array[0]) { return minnumberinrotatearray(arrays.copyofrange(array,array.length/2+1,array.length)); }else{ return minnumberinrotatearray(arrays.copyofrange(array,0,array.length/2+1)); } } }
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
解题思路:递归太慢,只能迭代。
public int fibonacci(int n) { if(n==0) return 0; int res = 1,tmp=1,tmp2=1; for(int i=2;i<n;i++) { res=tmp+tmp2; tmp2=tmp; tmp=res; } return res; }
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
解题思路:青蛙每次只有俩种结果。跳一次+1,跳俩阶+2
public int jumpfloor(int target) { if(target==0) return 0; if(target==1)return 1; if(target==2) return 2; return jumpfloor(target-1)+jumpfloor(target-2); }
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
解题思路:f(n) = 2^(n-1)
public class solution { public int jumpfloorii(int target) { return 1<<(target-1); } }
我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
解题思路:递归
public class solution { public int rectcover(int target) { if(target <=2){ return target; }else{ return rectcover(target-1) + rectcover(target-2); } } }
如对本文有疑问, 点击进行留言回复!!
《Oracle Java EE编程自学与面试指南》01-02、Web应用类型
Error: Avoided redundant navigation to current location: “/XXX“.的问题
Avoided redundant navigation to current location:
荐 四十一、Vue项目上手 | 用户管理系统 实现用户修改和删除功能(完成篇)
网友评论