题解 | #牛牛的顺时针遍历#

牛牛的顺时针遍历

https://www.nowcoder.com/practice/4c6722d907b147c7b73b51bdac768374?tpId=363&tqId=10618546&ru=/exam/oj&qru=/ta/super-company23Year/question-ranking&sourceUrl=%2Fexam%2Foj

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param matrix int整型二维数组
     * @return int整型一维数组
     */
    public int[] spiralOrder (int[][] matrix) {
        List<Integer> result = new ArrayList<>();

        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[0]; // 返回一个空数组
        }

        int m = matrix.length; // 矩阵的行数
        int n = matrix[0].length; // 矩阵的列数

        int top = 0; // 上边界
        int bottom = m - 1; // 下边界
        int left = 0; // 左边界
        int right = n - 1; // 右边界

        while (top <= bottom && left <= right) {
            // 遍历上边界从左到右
            for (int i = left; i <= right; i++) {
                result.add(matrix[top][i]);
            }
            top++;

            // 遍历右边界从上到下
            for (int i = top; i <= bottom; i++) {
                result.add(matrix[i][right]);
            }
            right--;

            // 在矩阵内部时遍历下边界从右到左
            if (top <= bottom) {
                for (int i = right; i >= left; i--) {
                    result.add(matrix[bottom][i]);
                }
                bottom--;
            }

            // 在矩阵内部时遍历左边界从下到上
            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    result.add(matrix[i][left]);
                }
                left++;
            }
        }

        int[] resArray = new int[result.size()];
        for (int i = 0; i < result.size(); i++) {
            resArray[i] = result.get(i);
        }

        return resArray;
    }
}

本题知识点分析:

1.数学模拟

2.数组遍历

3.集合转数组

4.集合存取

本题解题思路分析:

1.纯数学模拟

2.按照规则顺时针遍历,先从上边界开始,从左到右,然后从右边界开始,从上到下

3.此时判断左边界有没有超过右边界,判断是否已经遍历完毕

4.判断上边界有没有超过下边界,判断是否遍历完毕

本题使用编程语言: Java

如果你觉得对你有帮助的话,可以点个赞~

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务