螺旋数组

题目描述

给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序(顺时针)返回矩阵中的所有元素。
举例:
输入

[[1,2,3],[4,5,6],[7,8,9]]

输出

[1,2,3,6,9,8,7,4,5]

解题思路

数组模拟。顺时针打印,首先定义上下左右四个边界,每次遍历完一轮四个边界都要相应加1减1,每一轮遍历条件是上边界不超过下边界,左边界不超过右边界。要避免重复打印,在下、左遍历前要判断左右边界、上下边界。

Java实现

import java.util.*;
public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        //注意返回类型是ArrayList
        ArrayList<Integer> res = new ArrayList<>();
        //特殊情况判断,数组为空,直接返回空的res
        if (matrix.length == 0) {
            return res;
        }
        //定义上下左右边界
        int top = 0, bottom = matrix.length - 1, 
        left = 0, right = matrix[0].length - 1;
        //每一轮进行的条件是上边界不超过下边界,且左边界不超过右边界,每一轮顺序是上右下左
        while (top <= bottom && left <= right) {
            //从左到右遍历,执行完top加1
            for (int i = left; i <= right; i++) {
                res.add(matrix[top][i]);
            }
            top++;
            //从上到下遍历,执行完right减1
            for (int i = top; i <= bottom ; i++) {
                res.add(matrix[i][right]);
            }
            right--;
            if (top <= bottom) {
                //从右到左遍历,执行完bottom减1
                 for (int i = right; i >= left ; i--) {
                    res.add(matrix[bottom][i]);
                 }
            }
            bottom--;
            if (left <= right) {
                //从下到上遍历,执行完left加1
                for (int i = bottom; i >= top ; i--) {
                    res.add(matrix[i][left]);
                }
            }
            left++;
        }
        return res;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值