题解 | #牧场边界巡游#

牧场边界巡游

https://www.nowcoder.com/practice/bc7fe78f7bcc49a8bc0afdd7a55ca810

考察矩阵的螺旋遍历操作。

需要注意按照顺序更新边界上的元素

完整的Java代码如下所示

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param matrix int整型二维数组
     * @return int整型一维数组
     */
    public int[] spiralTravelCounterClockwise (int[][] matrix) {
        // write code here
        if (matrix.length == 0 || matrix[0].length == 0) {
            return new int[0];
        }

        ArrayList<Integer> resList = new ArrayList<>();
        int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;

        while (top <= bottom && left <= right) {
            for (int i = top; i <= bottom; i++) {
                resList.add(matrix[i][left]);
            }
            for (int j = left + 1; j <= right; j++) {
                resList.add(matrix[bottom][j]);
            }
            if (top < bottom && left < right) {
                for (int i = bottom - 1; i > top; i--) {
                    resList.add(matrix[i][right]);
                }
                for (int j = right; j > left; j--) {
                    resList.add(matrix[top][j]);
                }
            }
            top++;
            bottom--;
            left++;
            right--;
        }

        // 将ArrayList转换为int数组
        int[] res = new int[resList.size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = resList.get(i);
        }

        return res;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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