从下标变化的规律角度去解决二维数组的对角线打印问题。

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int[][] arr = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25}};
        System.out.println(Arrays.toString(arrayPrint(arr,5)));
    }
    public static int[] arrayPrint(int[][] arr, int n) {
        // write code here
        int[] array = new int[n*n];
        int index = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                array[index++] = arr[i][j];
            }
        }
        int[] ret = new int[n*n];
        int[] tmp = new int[n];
        int flush  = n,count = 2*n-1;
        for(int i = 0; i < n; i++) {
            tmp[i] = flush--;
        }
        int cur = 1,retI = 0;
        boolean flg = true;
        while (count-- > 0) {
            if(cur <= n && flg) {
                for (int i = cur-1; i >= 0; i--) {
                    ret[retI++] = array[tmp[i]-1];
                    if(tmp[i] <= n*n) {
                        tmp[i]+=n;
                    }
                }
                if(cur != n) {
                    cur++;
                }else {
                    cur--;
                    flg = false;
                }
            }else {
                for (int i = n-1; i >= n-cur; i--) {
                    ret[retI++] = array[tmp[i]-1];
                    if(tmp[i] <= n*n) {
                        tmp[i]+=n;
                    }
                }
                cur--;
            }
        }
        return ret;
    }
}

题目链接:https://www.nowcoder.com/questionTerminal/6fadc1dac83a443c9434f350a5803b51?toCommentId=921240
博主这种做法代码效率不是很高啊。在牛客的讨论区有高效率的解决方案。大家可以去看看。本人的代码在写的时候。没有构思好,结果写的很丑。但是博主想传达的其实是代码去实现打印二维数组对角线下标的一种思路。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值