题解 | #杨辉三角的变形#

杨辉三角的变形

http://www.nowcoder.com/practice/8ef655edf42d4e08b44be4d777edbf43

一 遍历杨辉三角左半部分(此方法运行到10000时提示越界,通过率73%)

import java.util.*;

public class YangHui {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] arr = new int[n][];
        for(int i = 0; i < arr.length; i++){
            arr[i] = new int[i+1];
            arr[i][0] = 1;
            for (int j = 1; j < arr[i].length; j++) {
                if(i <= 1){
                    arr[i][j] = 1;
                } else {
                    if(j == 1){
                        arr[i][j] = arr[i-1][j-1] + arr[i-1][j];
                    }
                    else if(j == arr[i].length - 1){
                        arr[i][j] = (arr[i-1][j-2] * 2) + arr[i-1][j-1];
                    }
                    else{
                        arr[i][j] = arr[i-1][j-2] + arr[i-1][j-1] + arr[i-1][j];
                    }
                }
            }
        }
        int index = -1;
        for (int j = 0; j < n ; j++) {
            if (arr[n - 1][j] % 2 == 0){
                index = j + 1;
                break;
            }
        }
        System.out.println(index);
    }
}

二 找规律(通过100%)

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
    /*
 1-  0            1
 2-  0            1 1
 3-  2            1 2 3
 4-  3            1 3 6 7
 5-  2            1 4 10 16 19
 6-  4            1 5 15 30 45 51
 7-  2            1 6 21 50 90 126 141
 8-  3            1 7 28 77 161 266 357 393
 9-  2            1 8 36 112 266 504 784 1016 1107
 10- 4            1 9 45 156 414 882 1554 2304 2907 3139
 
规律:
刨去前两行,每4行一个轮回,位数2,3,2,4循环;
     */
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int index = -1;
        if(n > 2){
            if((n-2) % 4 == 1 || (n-2) % 4 == 3){
                index = 2;
            }
            else if((n-2) % 4 == 2){
                index = 3;
            }
            else if((n-2) % 4 == 0){
                index = 4;
            }
        }
        System.out.println(index);
    }
}
全部评论
主要是题目中n的范围有点太大了,要是把n限制的小一点(500以内),第一种方法更通用,即便把题目改成第k个偶数也能给出答案。
点赞 回复 分享
发布于 2022-05-25 10:59

相关推荐

09-19 12:15
门头沟学院 Java
迷茫的大四🐶:这下是真的打牌了,我可以用感谢信和佬一起打牌吗
点赞 评论 收藏
分享
09-29 16:59
已编辑
门头沟学院 Java
牛客96609213...:疯狂背刺,之前还明确设置截止日期,还有笔试,现在一帮人卡在复筛,他反而一边开启扩招,还给扩招的免笔试,真服了,你好歹先把复筛中的给处理了再说
投递大疆等公司10个岗位
点赞 评论 收藏
分享
评论
4
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务