栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode腾讯精选练习50题-054.螺旋矩阵

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode腾讯精选练习50题-054.螺旋矩阵

目录
      • 题目描述
      • 解题思路 按层模拟
      • 代码(Java)

题目描述
  • 给定一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
example
input  : matrix = [[1,2,3],[4,5,6],[7,8,9]]
output : [1,2,3,6,9,8,7,4,5]

input  : matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
output : [1,2,3,4,8,12,11,10,9,5,6,7]
解题思路 按层模拟
  • 按照题目要求的转圈遍历顺序,使用上下左右四个界限坐标来标记每圈的位置,模拟整个向内环绕的元素获取过程。
  • 时间复杂度:O(m×n)
  • 空间复杂度:O(1)
代码(Java)
public class Solution {
    public List spiralOrder(int[][] matrix) {
        List list = new ArrayList<>();
        int length = matrix.length;
        int width = matrix[0].length;
        int left = 0, right = width - 1, top = 0, bottom = length - 1;
        while (left <= right && top <= bottom) {
            for (int i = left; i <= right; i++) {
                list.add(matrix[top][i]);
            }
            for (int j = top + 1; j <= bottom; j++) {
                list.add(matrix[j][right]);
            }
            if (left < right && top < bottom) {
                for (int p = right - 1; p >= left; p--) {
                    list.add(matrix[bottom][p]);
                }
                for (int q = bottom - 1; q > top; q--) {
                    list.add(matrix[q][left]);
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return list;
    }
}
暑期编程PK赛 得CSDN机械键盘等精美礼品!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1017179.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号