Created
June 6, 2020 23:32
-
-
Save bhaveshmunot1/b447616022d7032bdcdd1cfed5617ad0 to your computer and use it in GitHub Desktop.
Leetcode #1424: Diagonal Traverse II
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
vector<int> findDiagonalOrder(vector<vector<int>>& nums) { | |
vector<int> answer; | |
unordered_map<int, vector<int>> m; | |
int maxKey = 0; // maximum key inserted into the map i.e. max value of i+j indices. | |
for (int i=0; i<nums.size(); i++) { | |
for (int j=0; j<nums[i].size(); j++) { | |
m[i+j].push_back(nums[i][j]); // insert nums[i][j] in bucket (i+j). | |
maxKey = max(maxKey, i+j); // | |
} | |
} | |
for (int i=0; i<= maxKey; i++) { // Each diagonal starting with sum 0 to sum maxKey. | |
for (auto x = m[i].rbegin(); x != m[i].rend(); x++) { // print in reverse order. | |
answer.push_back(*x); | |
} | |
} | |
return answer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment