forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1329.cpp
More file actions
54 lines (40 loc) · 1.39 KB
/
1329.cpp
File metadata and controls
54 lines (40 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Problem: https://leetcode.com/problems/sort-the-matrix-diagonally/
class Solution {
public:
// HINT: Difference of j and i is constant across a diagonal.
vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {
int n = mat.size();
if (n <=1) return mat;
int m = mat[0].size();
map <int, vector<int>> mpp;
map <int, int> mpp2;
for (int i=0 ; i<n ; i++) {
for(int j=0 ; j<m ; j++) {
if(mpp.find(j-i)!=mpp.end()) {
vector<int> v = mpp[j-i];
v.push_back(mat[i][j]);
mpp[j-i] = v;
} else {
vector<int> v;
v.push_back(mat[i][j]);
mpp[j-i] = v;
}
}
}
for (auto it: mpp) {
vector<int> v = it.second;
sort(v.begin(), v.end());
mpp[it.first] = v;
mpp2[it.first] = 0;
}
for (int i=0 ; i<n ; i++) {
for(int j=0 ; j<m ; j++) {
int idx = mpp2[j-i];
vector<int>v = mpp[j-i];
mat[i][j] = v[idx];
mpp2[j-i] = idx+1;
}
}
return mat;
}
};