剑指offer之顺序打印数组
算法的要求为:#
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
解题的思路为:#
要求顺时针打印矩阵,打印的顺序为
遇到的问题#
我之前在写这个算法的过程中遇到了无法完整打印矩阵与数组指针越界的问题,我在仔细思考过后,发现时没有正确的处理在while
循环过程中的跳出操作。
其实应该在每一个for循环过后都要进行判断,判断left>right
或者up>down
,如果为true
,则说明矩阵已经打印完成,应该跳出while
循环。
代码的实现#
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> arr = new ArrayList<>();
if(matrix.length == 0 || matrix == null || matrix[0].length == 0) return arr;
int up = 0, left = 0;
int right = matrix[0].length-1, down=matrix.length-1;
while(true){
// 最上面的一行代码进行遍历
for(int i=left; i<=right; i++){
arr.add(matrix[up][i]);
}
up ++;
if(up > down) break;
//遍历最左边的一列
for(int i=up; i<=down; i++){
arr.add(matrix[i][right]);
}
right --;
if(left > right) break;
//遍历最底部一行
for(int i=right; i>= left; i--){
arr.add(matrix[down][i]);
}
down --;
if(up >down) break;
//遍历最左侧一列
for(int i=down; i>= up; i--){
arr.add(matrix[i][left]);
}
left ++;
if(left > right) break;
}
return arr;
}
}
作者:liulongtao
出处:https://www.cnblogs.com/liulongtao/p/13950772.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步