-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet-code-q-15.java
More file actions
49 lines (44 loc) · 1.37 KB
/
leet-code-q-15.java
File metadata and controls
49 lines (44 loc) · 1.37 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
class Solution {
public int[][] sortMatrix(int[][] grid) {
int n = grid.length;
// Bottom-left diagonals (including main diagonal) → descending
for (int startRow = n - 1; startRow >= 0; startRow--) {
List<Integer> diagonal = new ArrayList<>();
int r = startRow, c = 0;
while (r < n && c < n) {
diagonal.add(grid[r][c]);
r++;
c++;
}
// sort descending
diagonal.sort((a, b) -> b - a);
r = startRow; c = 0;
int pos = 0;
while (r < n && c < n) {
grid[r][c] = diagonal.get(pos++);
r++;
c++;
}
}
// Top-right diagonals → ascending
for (int startCol = 1; startCol < n; startCol++) {
List<Integer> diagonal = new ArrayList<>();
int r = 0, c = startCol;
while (r < n && c < n) {
diagonal.add(grid[r][c]);
r++;
c++;
}
// sort ascending
diagonal.sort(Integer::compareTo);
r = 0; c = startCol;
int pos = 0;
while (r < n && c < n) {
grid[r][c] = diagonal.get(pos++);
r++;
c++;
}
}
return grid;
}
}