zwkcoding / 100Days-Of-Leetcode

就像电影(500)Days of Summer一样,记录着每一天 Leetcode @itgoyo/500Days-Of-Github
0 stars 0 forks source link

14 2D_Array: Diagonal Traverse #19

Open zwkcoding opened 5 years ago

zwkcoding commented 5 years ago

Solution: Tips:

Notice: Time Complexity is (N+M)^2, Try to analyse. tips: use nested loops, multiply principle

/// O = O((N+M)^2)
vector<int> findDiagonalOrder(vector<vector<int>>& matrix)  {
    if(matrix.empty())  return {};

    const int n = matrix.size();
    const int m = matrix[0].size();

    vector<int> res;
    for(int s = 0; s <= n + m -2;  s++)  {
        int i = 0, j = 0;
        for(int x = 0; x <= s; x++)  {
            i = x;
            j = s - x;
            // when it is even, rever dir
            if(s % 2 == 0)  {
                swap(i, j);
            }
            // touch edge
            if(i >= n || j >= m) continue;
            res.push_back(matrix[i][j]);
        }
    }
    return res;
}