剑指 Offer编程题(二)

旋转数组

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0

import java.util.ArrayList;
public class Solution {
    public int minNumberInRotateArray(int [] array) {
        int front = 0;
        int rear = array.length-1;
        while(front<rear){
            int mid = (front+rear)/2;
            if(array[mid]>array[rear])
                front = mid+1;
            else if(array[mid]<array[rear])
                rear = mid;
            else
                rear = rear-1;
        }
      
        return array[front];
    }
}
斐波那契数列第n项

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39

public class Solution {
    public int Fibonacci(int n) {
        if(n == 0)
            return 0;
        else if(n == 1)
            return 1;
        else{
            int [] array = {0,1};
            for(int i=2; i<=n; i++){
                if(i%2 == 0)
                    array[0] = array[0] + array[1];
                else
                    array[1] = array[0] + array[1];
            }
            if(n%2 == 0)
                return array[0];
            else
                return array[1];
        }
    }
}

青蛙跳台阶

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

public class Solution {
    public int JumpFloor(int target) {
        if(target == 1)
            return 1;
        if(target == 0)
            return 1;
        return JumpFloor(target-1)+JumpFloor(target-2);
    }
}
高阶青蛙跳台阶

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

public class Solution {
    public int JumpFloorII(int target) {
        if(target == 0)
            return 0;
        if(target == 1)
            return 1;
        else{
            int sum = 0;
            return 2*JumpFloorII(target-1);
        }
    }
}
矩形填充

我们可以用21的小矩形横着或者竖着去覆盖更大的矩形。请问用n个21的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?

public class Solution {
    public int RectCover(int target) {
        if(target <= 0)
            return 0;
        else if(target == 1 || target == 2)
            return target;
        else{
            return RectCover(target-1)+RectCover(target-2);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值