题解 | #螺旋矩阵#

螺旋矩阵

https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {

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

        if(matrix.length == 0) return res;

        //分别记录上、下、左、右边界
        int up = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;
        while(up < (matrix.length + 1)/2 && left <  (matrix[0].length + 1)/2){
                //顺时针填充

                //1.填充上边界
                for(int i = left ; i <= right ; i++){
                    res.add(matrix[up][i]);
                }
                //2.填充右边界
                for(int i = up + 1 ; i <= bottom ; i++){
                    res.add(matrix[i][right]);
                }
                //3.填充下边界
                for(int i = right - 1 ; up != bottom && i >= left  ; i--){
                    res.add(matrix[bottom][i]);
                }
                //4.填充左边界
                for(int i = bottom - 1 ; left != right && i >= up + 1   ; i--){
                    res.add(matrix[i][left]);
                }

                up++;
                bottom--;
                left++;
                right--;
        }

        return res;
        
    }
}

全部评论

相关推荐

06-25 16:53
门头沟学院 Java
人力小鱼姐:简历可以直接用飞书模板 模拟面试可以试试ai,现在好多都还是免费阶段 像Sugar云面、多面鹅都不错,主要看面试后自己能不能复盘出有效信息
为了找工作你花了哪些钱?
点赞 评论 收藏
分享
废物一个0offer:认真的吗二本本科找人工智能岗位
点赞 评论 收藏
分享
就在我现在公司的隔壁每天经过都唏嘘不已(就是羡慕)什么时候可以到这里上班啊
柯基在debug:从大学毕业投简历到现在了,应届的时候我都面到终面了,现在工作四年了连简历初筛都过不了了
投递莉莉丝游戏等公司8个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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