O(n)级别的,一次遍历就完事,就是条件有点多
public class Solution { public int[][] generateMatrix(int n) { int num = n * n; int c = 0; int row = 1; int m = 1; int x = 0; int count = n; int[][] arr = new int[n][n]; for(int i = 1; i <= num; i++) { if(c >= 0 && c < count) { arr[row - 1][x++] = i; c ++; } else if(c >= count && c < count * 2 - 2) { arr[m++][n - row] = i; c ++; }else if(c >= count * 2 - 2 && c < count * 3 - 2) { arr[n - row][--x] = i; c ++; }else if(c >= count * 3 - 2 && c < count * 4 - 4){ arr[--m][row - 1] = i; c ++; } if(c == count * 4 - 4) { count = n - 2 * row; row++; x++; m++; c = 0; } } return arr; } }