题解 | #螺旋矩阵#

螺旋矩阵

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

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        //可以按照一层一层的来,转一圈,就把矩阵剥离了一层
        
        ArrayList<Integer> res = new ArrayList<>();
        if ( matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return res;
        }
        int row = matrix.length, column = matrix[0].length;
        // 四个顶角
        int left = 0, top = 0, right = column - 1, bottom = row - 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--;

            //  此处要再次判断一下顶角问题,因为把上方和右侧方剥离,可能就结束了,这样会重复添加元素
            if (left <= right && top <= bottom) {
                // 最后一行
                for (int i = right; i >= left; i--) {
                    res.add(matrix[bottom][i]);
                }
                bottom--;
                // 第一列
                for (int i = bottom; i >= top; i--) {
                    res.add(matrix[i][left]);
                }
                left++;
            }

        }
        return res;
    }

}

思路:首先要清楚螺旋矩阵,是怎么解开的,就是顺时针,一层一层剥离。因为可以进行迭代。用递归太耗时了。先固定四个顶点,left,right,top,bottom,然后一层while剥离顶行和最右列,再次检测四个顶点的满足条件,如果满足,再剥离底行和最左列,一层弄完,继续while循环。

全部评论

相关推荐

06-12 17:07
沈阳大学 Java
AAA射频小张:冬天也发扬下,我怕冷
点赞 评论 收藏
分享
叶扰云倾:进度更新,现在阿里云面完3面了,感觉3面答得还行,基本都答上了,自己熟悉的地方也说的比较细致,但感觉面试官有点心不在焉不知道是不是不想要我了,求阿里收留,我直接秒到岗当阿里孝子,学校那边的房子都退租了,下学期都不回学校,全职猛猛实习半年。这种条件还不诱人吗难道 然后现在约到了字节的一面和淘天的复活赛,外加猿辅导。华为笔试完没动静。 美团那边之前投了个base广州的,把我流程卡麻了,应该是不怎么招人,我直接简历挂了,现在进了一个正常的后端流程,还在筛选,不知道还有没有hc。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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