• 因此我只要定义上下左右四个边界,每一个方向的遍历都是一个 for 循环,循环好了之后需要转个向,此时移动对应的边界,并判断一下是否会越界即可!

    开干开干!

    首先任何题目,不管三七二之一,起手式:参数校验

     if (matrix == null 
              || matrix.length == 0 
              || matrix[0].length == 0
          return new int[0];

    然后把返回结果搞出来,就是个数组,大小就是矩阵的元素数。

     int[] res = new int[matrix.length * matrix[0].length];

    紧接着就是定义边界值了。

     int index = 0, left = 0, right = matrix[0].length - 1, top = 0, bottom = matrix.length - 1;

    万事俱备,紧接着就是核心逻辑了,按照箭头的走向,思路就是:

    一顿操作,完整代码如下:

    class Solution {
        public int[] spiralOrder(int[][] matrix) {
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0return new int[0];
            int[] res = new int[matrix.length * matrix[0].length];
            int index = 0, left = 0, right = matrix[0].length - 1, top = 0, bottom = matrix.length - 1;
            while (true) {
                for (int i = left; i <= right; i++) { //从左往右
                    res[index++] = matrix[top][i];
                }
                if (++top > bottom) break;  //top往下压一层
                for (int i = top; i <= bottom; i++) { //从上到下
                    res[index++] = matrix[i][right];
                }
                if (--right < left) break//right往左移一层
                for (int i = right; i >= left; i--) { //从右到左
                     res[index++] = matrix[bottom][i];
                }
                if (--bottom < top) break//bottom往上抬一层
                for (int i = bottom; i >= top; i--) { //从下到上
                    res[index++] = matrix[i][left];
                }
                if (++left > right) break//left往右移一层
            }
            return res; 
        }
    }

    面试官看了看代码:“时间复杂度和空间复杂度分别是多少呀?”

    我挺起胸膛,自信地回答道:“时间复杂度是O(MN),M是矩阵行数,N是列数。空间复杂度是O(1),只是定义了几个边界值而已。”

    面试官:“还能继续优化吗?”

    我:“.....”

    -END-


    总结来说,这题思路很清晰,就是要转换成代码,可能会遇到点阻碍。

    熟练了之后,这类题就是划边界,然后边界微操,注意一些细节。

    LeetCode地址:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/

    自己刷完了,可以去上面验证一下。

    搞个算法刷题群,报团取暖,有意者加我微信:yes_oba

    备注算法即可,白天比较忙,所以不会很快通过,请耐心等待。


    城北徐公,齐国之美丽者也出品,不定期更新,咱有缘再见。


    本文分享自微信公众号 - yes的练级攻略(yes_java)。
    如有侵权,请联系 support@oschina.cn 删除。
    本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

    07-18 19:46