zoukankan      html  css  js  c++  java
  • 498. Diagonal Traverse

    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

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    hadoop day 5
    SSM前言——相关设计模式
    多线程技术点二
    其他对象
    集合拾遗
    入职技术准备
    File类相关操作
    IO流技术
    多线程技术点
    第二章
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12693743.html
Copyright © 2011-2022 走看看