@author: sdubrz
@date: 7/31/2020 10:50:03 AM
难度: 简单
考察内容: 矩阵
@e-mail: lwyz521604#163.com
题目来自《剑指offer》 电子工业出版社
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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]
限制:
- 0 <= matrix.length <= 100
- 0 <= matrix[i].length <= 100
解法
可以螺旋式的一层一层剥皮:
class Solution {
public int[] spiralOrder(int[][] matrix) {
int n = matrix.length;
if(n==0) {
return new int[0];
}
int m = matrix[0].length;
int[] result = new int[n*m];
int direct = 1; // 1:left, 2:down, 3:left, 4:right
int count = 0;
// int start = 0;
int n_loop = Math.min((n+1)/2, (m+1)/2);
for(int start=0; start<n_loop; start++) {
// 一圈的上面一行
for(int i=start; i<m-start; i++) {
result[count] = matrix[start][i];
count++;
}
if(count>=n*m) {
break;
}
// 右边一列
for(int i=start+1; i<n-start-1; i++) {
result[count] = matrix[i][m-start-1];
count++;
}
if(count>=n*m) {
break;
}
// 下边一行
for(int i=m-start-1; i>=start; i--) {
result[count] = matrix[n-start-1][i];
count++;
}
if(count>=n*m) {
break;
}
// 左边一列
for(int i=n-start-2; i>start; i--) {
result[count] = matrix[i][start];
count++;
}
if(count>=n*m) {
break;
}
}
return result;
}
}
在 LeetCode 系统中提交的结果为
执行结果:通过 显示详情
执行用时:1 ms, 在所有 Java 提交中击败了97.04%的用户
内存消耗:40.9 MB, 在所有 Java 提交中击败了72.20%的用户