noaman_wgs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1、题目

//给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。 
//
//
//
// 示例 1:
//
//
//输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
//输出:[1,2,3,6,9,8,7,4,5]
//
//
// 示例 2:
//
//
//输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
//输出:[1,2,3,4,8,12,11,10,9,5,6,7]
//
//
//
//
// 提示:
//
//
// m == matrix.length
// n == matrix[i].length
// 1 <= m, n <= 10
// -100 <= matrix[i][j] <= 100
//
// Related Topics 数组
// 👍 611 👎 0




2、答案
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length <= 0) {
return new ArrayList<>();
}

ArrayList<Integer> result = new ArrayList<>();

int rowLen = matrix.length;
int colLen = matrix[0].length;

int right = colLen - 1;
int bottom = rowLen - 1;
int left = 0;
int top = 0;

int rowIndex = 0;
int colIndex = -1;
int total = rowLen * colLen;
int count = 0;
while (count < total) {
// 从左到右
for (int i = left; i <=right && count < total; i++) {
result.add(matrix[top][i]);
count++;
}

// 从上向下, 上+1
++top; // 向下一行
for (int i = top; i <= bottom && count < total; i++) {
result.add(matrix[i][right]);
count++;
}

// 从右向左,右-1
--right;
for (int i = right; i >= left && count < total; i--) {
result.add(matrix[bottom][i]);
count++;
}

// 从下到上,bottom-1
--bottom;
for (int i = bottom; i >= top && count < total; i--) {
result.add(matrix[i][left]);
count++;
}

left++;

}


return result;
}
}







posted on 2021-02-22 00:37  noaman_wgs  阅读(70)  评论(0编辑  收藏  举报