美团 二维数组打印

    xiaoxiao2026-09-02  2

    题目描述

    有一个二维数组(n*n),写程序实现从右上角到左下角沿主对角线方向打印。 给定一个二位数组arr及题目中的参数n,请返回结果数组。 测试样例: [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]],4 返回:[4,3,8,2,7,12,1,6,11,16,5,10,15,9,14,13]

    public int[] arrayPrint(int[][] arr, int n) { int[] res = new int[n * n]; int index = 0; for (int y = n - 1; y > 0; y--) { int i = 0; for (int j = y; j < n;) { res[index++] = arr[i++][j++]; } } for (int x = 0; x < n; x++) { int j = 0; for (int i = x; i < n; ) { res[index++] = arr[i++][j++]; } } return res; }
    转载请注明原文地址: https://ju.6miu.com/read-1311813.html
    最新回复(0)