前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Leetcode】54. 螺旋矩阵

【Leetcode】54. 螺旋矩阵

作者头像
Leetcode名企之路
发布2018-09-12 15:20:37
6690
发布2018-09-12 15:20:37
举报
文章被收录于专栏:Leetcode名企之路Leetcode名企之路

题目

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

代码语言:javascript
复制
输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]

示例 2:

代码语言:javascript
复制
输入:
[
  [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

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

代码语言:javascript
复制
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;
    }
}

每日英文

  • fiscal cliff 财政悬崖
  • monetary [a.]货币的
    • money 钱
  • IMF (International Monetary Fund) 国际货币基金
  • meaning (n.) 含义
  • meaningless (adj.) 无聊的,毫无意义的
    • -less 否定的后缀
  • well-meaning (adj.)好心的
  • meaningfully (adv.) 有意义地
  • meaningful (adj.) 有意义的
  • by means of 借助于(…的方法/工具)

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-08-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Leetcode名企之路 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 题解
  • 每日英文
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档