[每天刷 Leetcode-求组队] 54. 螺旋矩阵

2018-08-26 00:42:18 +08:00
 Acceml

题目

给定一个包含 m x n 个元素的矩阵( m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。 示例 1:

输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]

示例 2:

输入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]

题解

这个题目很简单,上下左右分别用四个变量去标志: 上:top 下:bottom 左:left 右: right

就按照四步走就可以:

  1. left -> right
  2. top -> bottom
  3. right -> left
  4. bottom -> top

每一步走完要对边界做出调整,具体看代码吧,清晰易懂。

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<Integer>();
        if (matrix.length == 0 || matrix[0].length == 0) return res;

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

        while (true) {
            for (int i = left; i <= right; i++) res.add(matrix[top][i]);
            top++;
            if (left > right || top > bottom) break;

            for (int i = top; i <= bottom; i++) res.add(matrix[i][right]);
            right--;
            if (left > right || top > bottom) break;

            for (int i = right; i >= left; i--) res.add(matrix[bottom][i]);
            bottom--;
            if (left > right || top > bottom) break;

            for (int i = bottom; i >= top; i--) res.add(matrix[i][left]);
            left++;
            if (left > right || top > bottom) break;
        }

        return res;
    }
}

热门阅读

4196 次点击
所在节点    C
32 条回复
snxq1995
2018-08-26 23:28:43 +08:00
开个群比较好交流,这样的公众号其他人参与度不高。
ayyll
2018-08-27 07:53:58 +08:00
@Acceml leetcode 太水了 真谈算法能力 还是上 tc/cf 吧 打到 rank 前 10 标准的青年计算机科学家
Acceml
2018-08-27 09:47:36 +08:00
@snxq1995 好滴~~
Acceml
2018-08-27 09:48:22 +08:00
@yumenawei 看看再跳呗。
Acceml
2018-08-27 09:52:44 +08:00
@ayyll 我的初衷就是为了准备下面试,我认为算法能力和工程能力完全不等价。不会花很多时间在上面,你所谓的水在我看来足够即可。
Elephant696
2018-08-27 09:58:19 +08:00
这个题,,,以前面试的时候二面面试官叫我用笔手写这个算法,,,我当时告诉他说我只能说思路,手写写不出来,然后被对方请出去了,没错,是请出去了。记忆深刻。
PS:我面试是前端。。。
coffeSlider
2018-08-27 11:36:32 +08:00
这个题只用一个变量就能解呢
Acceml
2018-08-27 13:26:11 +08:00
@Elephant696 哪家面试官,这么虎的吗?
Acceml
2018-08-27 13:26:33 +08:00
@coffeSlider 用一个变量,需要记住走的步数?
coffeSlider
2018-08-27 13:55:51 +08:00
@Acceml 简单的来说,就是用一个数来记录四个方向和走了几圈
ayyll
2018-08-27 15:40:43 +08:00
@Acceml 行 8 good luck
Elephant696
2018-08-28 16:20:18 +08:00
@Acceml 一个创业公司,名字就不说了。太菜了不敢大声说话

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/483264

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX