zoukankan      html  css  js  c++  java
  • 【LeetCode-数组】螺旋矩阵(顺时针打印矩阵)

    题目描述

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

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

    题目链接: https://leetcode-cn.com/problems/spiral-matrix/

    思路

    使用和螺旋矩阵II类似的方法:设置 4 个变量:t、b、l、r,分别表示当前上下左右的范围。然后遍历不断缩小范围,具体见代码,要注意循环的结束条件:

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            if(matrix.empty()) return {};
    
            int t = 0;
            int b = matrix.size()-1;
            int l = 0;
            int r = matrix[0].size()-1;
    
            vector<int> ans;
            while(true){
                for(int i=l; i<=r; i++) ans.push_back(matrix[t][i]);
                t++;
                if(t>b) break;
    
                for(int i=t; i<=b; i++) ans.push_back(matrix[i][r]);
                r--;
                if(r<l) break;
    
                for(int i=r; i>=l; i--) ans.push_back(matrix[b][i]);
                b--;
                if(b<t) break;
    
                for(int i=b; i>=t; i--) ans.push_back(matrix[i][l]);
                l++;
                if(l>r) break;
            }
            return ans;
        }
    };
    
    • 时间复杂度:O(m x n)
      m、n 为行列数。
    • 空间复杂度:O(1)
  • 相关阅读:
    第三个Sprint冲刺第三天
    回答第1-17章
    阅读第13-17章
    阅读第10、11、12章
    阅读第8,9,10章
    作业5.2 5.3
    四则运算 测试与封装 5.1
    阅读第5-7章
    阅读1-5章
    我给队友做的汉堡包
  • 原文地址:https://www.cnblogs.com/flix/p/13257779.html
Copyright © 2011-2022 走看看