首页 > 其他 > 详细

498. Diagonal Traverse

时间:2020-04-13 22:00:32      阅读:84      评论:0      收藏:0      [点我收藏+]

Problem:

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:

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

思路

Solution (C++):

vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
    if (matrix.empty())  return {};
    int m = matrix.size(), n = matrix[0].size();
    vector<vector<int>> tmp(m+n-1);
    
    for (int i = 0; i < m+n-1; ++i) {
        int row = max(0, i-n+1);
        int col = min(i, n-1);
        for (; row < m && col >= 0 ; ++row, --col) {
            tmp[i].push_back(matrix[row][col]);
        }
    }
    
    vector<int> res;
    for (int i = 0; i < m+n-1; ++i) {
        if (i & 1)  res.insert(res.end(), tmp[i].begin(), tmp[i].end());
        else  res.insert(res.end(), tmp[i].rbegin(), tmp[i].rend());
    }
    return res;
}

性能

Runtime: 116 ms??Memory Usage: 16.9 MB

思路

Solution (C++):


性能

Runtime: ms??Memory Usage: MB

498. Diagonal Traverse

原文:https://www.cnblogs.com/dysjtu1995/p/12693743.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!