剑指 Offer 29. 顺时针打印矩阵
遍历,设置边界
执行用时:1 ms, 在所有 Java 提交中击败了97.38% 的用户 内存消耗:39.6 MB, 在所有 Java 提交中击败了73.08% 的用户
class Solution {public int[] spiralOrder(int[][] matrix) {if (matrix.length == 0) return new int[0];// 设置边界int left = 0, right = matrix[0].length - 1, top = 0, bottom = matrix.length - 1;int index = 0;int[] res = new int[(right + 1) * (bottom + 1)];while (true) {// left to rightfor (int i = left; i <= right; i++)res[index++] = matrix[top][i];if(++top > bottom) break;// top to bottomfor (int i = top; i <= bottom; i++)res[index++] = matrix[i][right];if (--right < left) break;// right to leftfor (int i = right; i >= left; i--)res[index++] = matrix[bottom][i];if (--bottom < top) break;// bottom to topfor (int i = bottom; i >= top; i--)res[index++] = matrix[i][left];if (++left > right) break;}return res;}}
