顺时针打印矩阵

博客提及力扣按层模拟算法,分析其时间复杂度与行数、列数相关,空间复杂度因用到的变量数量有限。还指出要先判断数组是否为空,空数组直接返回,循环中需判断top<= bottom和left <= right,避免重复插入。

力扣地址

按层模拟:

时间复杂度:O\left ( m*n \right ),m和n是行数和列数

空间复杂度:O\left ( 1 \right ),用到的left,right,top,bottom数量有限,res是结果,所以是O\left ( 1 \right )

首先判断数组,空数组直接返回

难点在于边界问题,在循环中需要判断 top<= bottom 和 left <= right,防止重复插入

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int row = matrix.size();
        if (!row) return {};
        int col = matrix[0].size();
        if (!col) return {};
        int left = 0, right = col - 1;
        int top = 0, bottom = row - 1;
        vector<int> res;
        res.reserve(row * col);
        while (left <= right && top <= bottom) {
            for (int i = left; i <= right; ++i) {
                res.push_back(matrix[top][i]);
            }
            ++top;
            for (int i = top; i <= bottom; ++i) {
                res.push_back(matrix[i][right]);
            }
            --right;
            if (top <= bottom) {
                for (int i = right; i >= left; --i) {
                    res.push_back(matrix[bottom][i]);
                }
                --bottom;
            }
            if (left <= right) {
                for (int i = bottom; i >= top; --i) {
                    res.push_back(matrix[i][left]);
                }
                ++left;
            }
        }
        return res;
    }
};

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值