用时40min
物理上x,y坐标和二维数组中第一维第二维的关系易错注意边界条件 class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> result = new ArrayList<Integer>(); if(matrix.length == 0 || matrix[0].length == 0) return result; int x1 = 0,y1 = 0,cx = 0,cy = 0; int x2 = matrix.length-1, y2 = matrix[0].length-1; int count = matrix.length * matrix[0].length; while((count--)!=0){ result.add(matrix[cx][cy]); if(cy < y2 && cx == x1) cy ++; else if(cy == y2 && cx < x2) cx ++; else if(cx == x2 && cy > y1) cy --; else if(cy == y1 && cx > x1) { if(cx == (x1+1)) { x1++; y1++; x2--; y2--; cy += 1; } else cx--; } } return result; } } 这道题首先要注意的是物理上的x坐标在二维数组中并不是对应于第一维,而是第二维,y坐标对应的是二维数组中第一维。首先这一点不能出错实际上将一个矩阵分解成若干个环绕,依次进行遍历