leetcode146. 螺旋遍历二维数组(java)

class Solution {
    public int[] spiralArray(int[][] array) {
        int n = array.length;
        if(n==0){
            return new int[0];
        }
           int m = array[0].length;
           int[] nums = new int[n*m];
        int len = 0;
        int top=0;
        int bottom = n-1;
        int left = 0;
        int right = m-1;
        int j=0;
        int i = 0;
        while(len<n*m){
            for(j=left;j<=right&&len<n*m;j++){
                nums[len++]=array[top][j];
            }
            top++;
            for(i=top;i<=bottom&&len<n*m;i++){
                nums[len++]=array[i][right];
            }
            right--;
            for(j=right;j>=left&&len<n*m;j--){
                nums[len++]=array[bottom][j];
            }
            bottom--;
            for(i=bottom;i>=top&&len<n*m;i--){
                nums[len++]=array[i][left];
            }
            left++;
        }






        return nums;
    }
}

 思路:设置上下左右各4个边界变量,每个循环的判断条件记得加上len<n*m,否则会有越界错误。

坑1:如果循环判断条件没加上len<n*m,比如当array=[[1,2]]时,第三个for循环条件成立会执行,此时len已经是3了,越界。

坑2:当array为空时,返回空数组new int[0];

提交,通过!

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值