题解 | #顺时针打印矩阵#
顺时针打印矩阵
http://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
O(N),此题中N代表二维数组中的元素个数
似乎只有模拟,就顺时针打印,循环不变量很重要,确保左闭右开,左闭右闭也行,反正每次循环保持一致
此题中最后要处理不够循环一周的情况,三种情况,1,剩一个,2剩一行,3剩一列,但是情况1包含在情况2和3中。用loop来标记循环周数的情况,且此题没有说明一定是方阵,所以行列分别有两个变量进行约束
import java.util.*;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
//模拟,循环不变量
ArrayList<Integer> res = new ArrayList<>();
int loop = Math.min(matrix.length, matrix[0].length) / 2;//mark
int hor = 0;//行
int hor1 = matrix.length-1;
int col = 0;//列
int col1 = matrix[0].length - 1;
while (loop != 0) {
for (int j = hor; j<col1; j++) {//左到右 [左闭右开)
res.add(matrix[hor][j]);
}
for (int i = hor; i<hor1; i++) {//上到下
res.add(matrix[i][col1]);
}
for (int j = col1; j>col; j--) {//右到左
res.add(matrix[hor1][j]);
}
for (int i = hor1; i>hor; i--) {//下到上
res.add(matrix[i][col]);
}
hor++;
hor1--;
col++;
col1--;
loop--;
}
if(hor == hor1){//剩一行(包括剩一个)
for(int i = col; i <= col1; i++) res.add(matrix[hor][i]);
}else if(col == col1){//剩一列
for(int i = hor; i <= hor1; i++) res.add(matrix[i][col]);
}
return res;
}
}