顺时针打印矩阵_JAVA_较难

顺时针打印矩阵

http://www.nowcoder.com/questionTerminal/9b4c81a02cd34f76be2659fa0d54342a

  • 从上、右、下、左四条边依次输出,每次输出起点而不输出终点
  • 确保单行单列情况下不逆行,则单行单列情况下会缺少输出终点
  • 则在循环外补充单行单列情况下未输出的终点
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> res = new ArrayList();
        int startI = 0, startJ = 0, endI = matrix.length - 1, endJ = 0;
        if(startI > endI) {
            return res;
        }
        endJ = matrix[0].length - 1;

        // 直到输出完
        int i = 0, j = 0;
        while(startI <= endI && startJ <= endJ) {
            i = startI;
            j = startJ;
            // 上面的一条
            while(j < endJ) {
                res.add(matrix[i][j++]);
            }
            // 右侧的一条
            while(i < endI) {
                res.add(matrix[i++][j]);
            }
            // 下面的一条,禁止单行逆行
            while(startI != endI && j > startJ) {
                res.add(matrix[i][j--]);
            }
            // 左侧的一条,禁止单列逆行
            while(startJ != endJ && i > startI) {
                res.add(matrix[i--][j]);
            }
            startI++;
            startJ++;
            endI--;
            endJ--;
        }

        // 将最后单独的一个输出
        if(--startI == ++endI || --startJ == ++endJ) {
            res.add(matrix[i][j]);
        }
        return res;
    }
}
全部评论

相关推荐

这不纯纯作弊了吗😢😢😢
编程界菜鸡:信这个的这辈子有了,这智商你靠啥都没用
点赞 评论 收藏
分享
06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
07-02 18:09
门头沟学院 Java
苍穹外卖和谷粒商城这俩是不是烂大街了,还能做吗?
想去重庆的鸽子在吐槽:你不如把这俩做完自己搞明白再优化点再来问 何必贩卖焦虑
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务