Java数组打印金字塔数列:如何用Java创建一个包含1,1,2,1,2,3...1,2,3...n元素的数组?

java使用array打印金字塔数列

问题:

要求编写一个方法,给定一个整数n,生成一个包含[1,1,2,1,2,3

,..... 1, 2, 3,…n]元素的array,array长度为1 2 3… n=n*(n 1)/2。比如:arithseries(3) → [1, 1, 2, 1, 2, 3]

代码:

public static int[] arithSeries(int n) {
    int resultLength = n * (n + 1) / 2; // length of result array
    int[] result = new int[resultLength]; // initialise array
    int pointer = 0; // the position of array
    for (int i = 1; i <= n; i++) { // if i start from 1 then the end condition should be <=n
        for (int j = 1; j <= i; j++) {// assign value from 1 to i
            result[pointer] = j;
            pointer++;// move to next pointer
        }
    }
    return result;
}