跳转至

498.Diagonal Traverse

Tags: Medium Hash Table

Links: https://leetcode.com/problems/diagonal-traverse/


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.


class Solution {
public:
    vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        vector<int> res;
        unordered_map<int, vector<int>> um;
        int m = matrix.size(); if (!m) return res;
        int n = matrix[0].size(); if (!n) return res;

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                um[i + j].push_back(matrix[i][j]);
            }
        }

        int level = 1;
        for (int i = 0; i < m + n - 1; ++i) {
            if (level & 1) {
                vector<int> & tmp = um[i];
                int len = tmp.size();
                for (int j = len - 1; j >= 0; --j) res.push_back(tmp[j]); 
            }
            else {
                vector<int> & tmp = um[i];
                int len = tmp.size();
                for (int j = 0; j < len; ++j) res.push_back(tmp[j]);
            }
            ++level;
        }

        return res;
    }
};

和LeetCode周赛1424题目基本一致,八皇后的变形,处于同意对角线的元素行号+列号相同。所以用一个unordered_map来存储,用一个变量level来记录层数,根据奇偶性的不同来选择是否翻转。