看到通过率比二还低就做了,其实思路基本一样,主要是要记录一个数据填了多少,超出的时候退出循环。
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0) {
return result;
}
int m = matrix.length;
int n = matrix[0].length;
int top = 0;
int bottom = m - 1;
int left = 0;
int right = n - 1;
int k = 0;
while (k < m * n) {
for (int i = left; i <= right && k < m * n; i++) {
result.add(matrix[top][i]);
k++;
}
top++;
for (int i = top; i <= bottom && k < m * n; i++) {
result.add(matrix[i][right]);
k++;
}
right--;
for (int i = right; i >= left && k < m * n; i--) {
result.add(matrix[bottom][i]);
k++;
}
bottom--;
for (int i = bottom; i >= top && k < m * n; i--) {
result.add(matrix[i][left]);
k++;
}
left++;
}
return result;
}