做网站建设专业定制,wordpress -editor,购物平台app,南宁网站建站LCR 146. 螺旋遍历二维数组
给定一个二维数组 array#xff0c;请返回「螺旋遍历」该数组的结果。
螺旋遍历#xff1a;从左上角开始#xff0c;按照 向右、向下、向左、向上 的顺序 依次 提取元素#xff0c;然后再进入内部一层重复相同的步骤#xff0c;直到提取完所有… LCR 146. 螺旋遍历二维数组
给定一个二维数组 array请返回「螺旋遍历」该数组的结果。
螺旋遍历从左上角开始按照 向右、向下、向左、向上 的顺序 依次 提取元素然后再进入内部一层重复相同的步骤直到提取完所有元素。
示例 1
输入array [[1,2,3],[8,9,4],[7,6,5]]
输出[1,2,3,4,5,6,7,8,9]class Solution {public int[] spiralArray(int[][] array) {if (array null || array.length 0 || array[0].length 0) {return new int[0];}int rows array.length, columns array[0].length;int[] order new int[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] array[top][column];}for (int row top1; row bottom; row) {order[index] array[row][right];}if (left right top bottom) {for (int column right-1; column left; column--) {order[index] array[bottom][column];}for (int row bottom; row top; row--) {order[index] array[row][left];}}left;right--;top;bottom--;}return order;}
} 54. 螺旋矩阵
class Solution {public ListInteger spiralOrder(int[][] matrix) {ListInteger order new ArrayListInteger();if(matrix null || matrix.length 0 || matrix[0].length 0){return order;}int rows matrix.length, cols matrix[0].length;int left 0,right cols - 1,top 0,bottom rows -1;while(left right top bottom){for(int colleft;colright;col){order.add(matrix[top][col]);}for(int row top1;row bottom;row){order.add(matrix[row][right]);}if(left right top bottom){for(int col right -1;col left;col--){order.add(matrix[bottom][col]);}for(int row bottom;row top ;row--){order.add(matrix[row][left]);}}left;right--;top;bottom--;}
return order;}
}