题解 | 螺旋矩阵

螺旋矩阵

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param matrix int整型二维数组
     * @return int整型ArrayList
     */
    public ArrayList<Integer> spiralOrder (int[][] matrix) {
        // write code here
        if (matrix.length == 0) return new ArrayList<>();
        ArrayList<Integer> res = new ArrayList<>();
        // 定义矩形的四个边,想象成一条直线,不要想象成某个点
        // top/bottom就是行级别的,left和right就是列级别的
        int top = 0, bottom = matrix.length - 1;
        int left = 0, right = matrix[0].length - 1;

        while (left <= right && top <= bottom) {
            // 从左到右
            for (int i = left; i <= right; i++) {
                res.add(matrix[top][i]);
            }
            top++;

            // 从上到下
            for (int i = top; i <= bottom; i++) {
                res.add(matrix[i][right]);
            }
            right--;

            // 若存在合理下边界,则遍历下边界,因为前面top/bottom中的top值有变化
            if (top <= bottom) {
                // 从左到右
                for (int i = right; i >= left; i--) {
                    res.add(matrix[bottom][i]);
                }
                bottom--;
            }

            // 若存在合理左边界,则遍历左边界,因为前面left/right中的right值有变化
            if (left <= right) {
                // 从下到上
                for (int i = bottom; i >= top; i--) {
                    res.add(matrix[i][left]);
                }
                left++;
            }

        }

        return res;
    }
}

全部评论

相关推荐

10-19 00:57
门头沟学院 Java
我不是嘉心糖捏:我刚收到面试捏
投递360集团等公司10个岗位
点赞 评论 收藏
分享
11-06 16:50
门头沟学院 Java
用微笑面对困难:word打字比赛二等奖的我,也要来凑合凑合
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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