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
博主这种做法代码效率不是很高啊。在牛客的讨论区有高效率的解决方案。大家可以去看看。本人的代码在写的时候。没有构思好,结果写的很丑。但是博主想传达的其实是代码去实现打印二维数组对角线下标的一种思路。