Skip to content

Instantly share code, notes, and snippets.

@bhaveshmunot1
Created June 6, 2020 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhaveshmunot1/b447616022d7032bdcdd1cfed5617ad0 to your computer and use it in GitHub Desktop.
Save bhaveshmunot1/b447616022d7032bdcdd1cfed5617ad0 to your computer and use it in GitHub Desktop.
Leetcode #1424: Diagonal Traverse II
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