设为首页 加入收藏

TOP

再来五道剑指offer题目
2019-09-25 18:11:30 】 浏览:31
Tags:offer 题目

再来五道剑指offer题目

6、旋转数组的最小数字

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{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));
        }
    }
}

7、斐波那契数列

大家都知道斐波那契数列,现在要求输入一个整数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;
    }

8、跳台阶

一只青蛙一次可以跳上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);
    }

9、变态跳台阶

一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

解题思路:f(n) = 2^(n-1)

public class Solution {
    public int JumpFloorII(int target) {
        return 1<<(target-1);
    }
}

10、矩形覆盖

我们可以用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);
        }
    }
}
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Incorrect datetime value: '.. 下一篇面试官之问:知道你的接口“QPS”..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目