C++ solution using a hash table to store the diagonals


  • 0
    G
    class Solution {
    public:
        vector<int> findDiagonalOrder(vector<vector<int>>& matrix) 
        {
            unordered_map<int,vector<int> > M;
            
            for(int i = 0; i < matrix.size(); ++i)
            {
                for(int j = 0; j < matrix[i].size(); ++j)
                {
                    M[i + j].push_back(matrix[i][j]);
                }
            }
            
            for(auto &P : M)
            {
                if((P.first % 2) == 0)
                {
                    reverse(P.second.begin(),P.second.end());
                }
            }
            
            vector<int> Result;
            
            if(matrix.empty())
            {
                return (Result);
            }
            
            for(int i = 0; i < matrix.size() + matrix[0].size() - 1; ++i)
            {
                Result.insert(Result.end(),M[i].begin(),M[i].end());
            }
            
            return (Result);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.