科大讯飞提前批测试笔试

剪绳子:
输入:
6
输出:9
java代码:

import java.util.Scanner;
public class Main1111 {
    public static void main(String[] args) {


        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {// 注意,如果输入是多个测试用例,请通过while循环处理多个测试用例

            int n = in.nextInt();
            //System.out.println(a);

            int[] dp = new int[n + 1];


            dp[0] = 0;
            dp[1] = 1;
            dp[2] = 2;
            dp[3] = 3;
            dp[4] = 4;



            if(n <= 4){
                System.out.println(dp[n]);
            }
            else{

                for(int i = 5; i <= n; i++){

                    for(int j = 1; j < i; j++){

                        //写出状态转移方程

                        dp[i] = Math.max(dp[i], dp[j] * dp[i - j]);


                    }


                }
                System.out.println(dp[n]);


            }

        }
    }
}

递归的二分查找:
输入:
6
11 13 15 16 19 21
19
输出
4

import java.util.Scanner;

public class TwoFind {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();

        int[] temp = new int[n];

        int ans = 0;

        for(int i = 0; i < n; i++){


            temp[i] = sc.nextInt();

        }

        int target = sc.nextInt();
//        System.out.println(target);
        int left = 0;
        int right = temp.length - 1;

        ans = twofind(temp,target, left, right);

        System.out.println(ans);

    }


    private static int twofind(int[] a, int target, int left, int right){

        //数组有序,可以用二分查找,递归的二分查找,相当于快速排序

        int mid = (left + right)/ 2;

        int de;

        if(left > right){
            return -1;
        }


        if(a[mid] == target){
//            System.out.println(mid);
            return mid;
        }

//        System.out.println(mid);

        if(a[mid] < target){
            //跑右边
            de = twofind(a, target, left = mid + 1, right);
        }

        else{
            de = twofind(a, target, left, right = mid - 1);
        }

        return de;



    }




}

你可能感兴趣的:(面试,java)