?]后台的网站可以备案吗,wordpress永久链接,wordpress 文章带字段,做团购的家居网站有哪些给定一个二维数组 array#xff0c;请返回「螺旋遍历」该数组的结果。
螺旋遍历#xff1a;从左上角开始#xff0c;按照 向右、向下、向左、向上 的顺序 依次 提取元素#xff0c;然后再进入内部一层重复相同的步骤#xff0c;直到提取完所有元素。
示例 1#xff1a;…给定一个二维数组 array请返回「螺旋遍历」该数组的结果。
螺旋遍历从左上角开始按照 向右、向下、向左、向上 的顺序 依次 提取元素然后再进入内部一层重复相同的步骤直到提取完所有元素。
示例 1
输入array [[1,2,3],[8,9,4],[7,6,5]]
输出[1,2,3,4,5,6,7,8,9]
示例 2
输入array [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
输出[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] 解【一开始做的时候arr用的是一维数组一直不过改成返回值是ListInteger就好了】
class Solution {public ListInteger spiralOrder(int[][] matrix) {
int topRow 0, bottomRow matrix.length - 1; // 定义上边界和下边界int leftCol 0, rightCol matrix[0].length - 1; // 定义左边界和右边界int direction 0; // 初始方向0代表向右
ListInteger arr new ArrayList();while (topRow bottomRow leftCol rightCol) {if (direction 0) { // 向右for (int i leftCol; i rightCol; i) {arr.add(matrix[topRow][i]);}topRow; // 上边界下移} else if (direction 1) { // 向下for (int i topRow; i bottomRow; i) {arr.add(matrix[i][rightCol]);}rightCol--; // 右边界左移} else if (direction 2) { // 向左for (int i rightCol; i leftCol; i--) {arr.add(matrix[bottomRow][i]);}bottomRow--; // 下边界上移} else if (direction 3) { // 向上for (int i bottomRow; i topRow; i--) {arr.add(matrix[i][leftCol]);}leftCol; // 左边界右移}direction (direction 1) % 4; // 切换方向}return arr;}
}