54、数组--模拟

LCR 146. 螺旋遍历二维数组

给定一个二维数组 array,请返回「螺旋遍历」该数组的结果。

螺旋遍历:从左上角开始,按照 向右向下向左向上 的顺序 依次 提取元素,然后再进入内部一层重复相同的步骤,直到提取完所有元素。

示例 1:

输入:array = [[1,2,3],[8,9,4],[7,6,5]]
输出:[1,2,3,4,5,6,7,8,9]
class Solution {
    public int[] spiralArray(int[][] array) {
        if (array == null || array.length == 0 || array[0].length == 0) {
            return new int[0];
        }
        int rows = array.length, columns = array[0].length;
        int[] order = new int[rows * columns];
        int index = 0;
        int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
        while (left <= right && top <= bottom) {
            for (int column = left; column <= right; column++) {
                order[index++] = array[top][column];
            }
            for (int row = top+1; row <= bottom; row++) {
                order[index++] = array[row][right];
            }
            if (left < right && top < bottom) {
            for (int column = right-1; column > left; column--) {
                order[index++] = array[bottom][column];
            }
            for (int row = bottom; row > top; row--) {
                order[index++] = array[row][left];
            }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return order;

    }
}

 

54. 螺旋矩阵

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> order = new ArrayList<Integer>();
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return order;
           
        }
        int rows = matrix.length, cols = matrix[0].length;
        int left =0,right = cols - 1,top =0,bottom = rows -1;
        while(left <= right && top <= bottom){
            for(int col=left;col<=right;col++){
                order.add(matrix[top][col]);
            }
            for(int row = top+1;row<= bottom;row++){
                order.add(matrix[row][right]);
            }
            if(left < right && top < bottom){
                for(int col = right -1;col > left;col--){
                    order.add(matrix[bottom][col]);
                }
                for(int row = bottom;row > top ;row--){
                    order.add(matrix[row][left]);
                }
            }
            left++;
            right--;
            top++;
            bottom--;

        }
return order;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值