classSolution{publicint[]spiralOrder(int[][] matrix){if(matrix == null || matrix.length ==0|| matrix[0].length ==0){returnnewint[0];}int rows = matrix.length, columns = matrix[0].length;int[] order =newint[rows * columns];int index =0;int left =0, right = columns -1, top =0, bottom = rows -1;while(left <= right && top <= bottom){for(int column = left; column <= right; column++){order[index++]= matrix[top][column];}for(int row = top +1; row <= bottom; row++){order[index++]= matrix[row][right];}//判斷必不可少 if(left < right && top < bottom){for(int column = right -1; column > left; column--){order[index++]= matrix[bottom][column];}for(int row = bottom; row > top; row--){order[index++]= matrix[row][left];}}left++;right--;top++;bottom--;}return order;}}
解釋二
時間復雜度:O(NM) 空間復雜度:O(NM)
classSolution{publicint[]spiralOrder(int[][] matrix){if(matrix.length ==0)returnnewint[0];int l =0, r = matrix[0].length -1, t =0, b = matrix.length -1, x =0;int[] res =newint[(r +1)*(b +1)];while(true){for(int i = l; i <= r; i++) res[x++]= matrix[t][i];// left to right.if(++t > b)break;for(int i = t; i <= b; i++) res[x++]= matrix[i][r];// top to bottom.if(l >--r)break;for(int i = r; i >= l; i--) res[x++]= matrix[b][i];// right to left.if(t >--b)break;for(int i = b; i >= t; i--) res[x++]= matrix[i][l];// bottom to top.if(++l > r)break;}return res;}}