[Leetcode] 498. Diagonal Traverse 解题报告

这篇博客介绍了LeetCode第498题的解题报告,题目要求按对角线顺序返回矩阵的所有元素。作者强调了处理边界情况的重要性,并分享了具有O(m*n)时间复杂度和O(1)空间复杂度的解决方案代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.

Example:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output:  [1,2,4,7,5,3,6,8,9]
Explanation:

Note:

  1. The total number of elements of the given matrix will not exceed 10,000.

思路

题目的难度不大,但是需要注意各种边界情况。读者可以重点研究一下for循环里面的四个if语句。算法的时间复杂度是O(m*n),空间复杂度是O(1)。

代码

class Solution {
public:
    vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
        if (matrix.size() == 0 || matrix[0].size() == 0) {
            return {};
        }
        int row_num = matrix.size(), col_num = matrix[0].size();
        vector<int> ret;
        int row = 0, col = 0, d = 0;
        vector<vector<int>> dirs = {{-1, 1}, {1, -1}};
        for (int i = 0; i < row_num * col_num; ++i) {
            ret.push_back(matrix[row][col]);
            row += dirs[d][0], col += dirs[d][1];
            if (row >= row_num) {       // from down to up
                row = row_num - 1, col += 2, d = 1 - d;
            }
            if (col >= col_num) {       // from up to down
                col = col_num - 1, row += 2, d = 1 - d;
            }
            if (row < 0) {              // from up to down
                row = 0, d = 1 - d;
            }
            if (col < 0) {              // from down to up
                col = 0, d = 1 - d;
            }
        }
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值