1.二维数组声明 int[][] ans=new int[n][n];
2. left <= right && top <= bottom 跳出循环条件
1 class Solution { 2 public int[][] generateMatrix(int n) { 3 int[][] ans=new int[n][n]; 4 int num=1; 5 int top=0,bottom=n-1,left=0,right=n-1; 6 while(left <= right && top <= bottom){ 7 for(int i=left;i<=right;i++){ 8 ans[top][i]=num++; 9 } 10 top++; 11 for(int i=top;i<=bottom;i++){ 12 ans[i][right]=num++; 13 } 14 right--; 15 if(left<=right){ 16 for(int i=right;i>=left;i--){ 17 ans[bottom][i]=num++; 18 } 19 } 20 bottom--; 21 if(top<=bottom){ 22 for(int i=bottom;i>=top;i--){ 23 ans[i][left]=num++; 24 } 25 } 26 left++; 27 } 28 return ans; 29 } 30 }
标签:bottom,int,top,矩阵,LeetCode59,Q14,num,ans,left From: https://www.cnblogs.com/cff1/p/18238044