Skip to content

Commit a32c1c3

Browse files
authored
2022-08-28 update: added "Sort the Matrix Diagonally" (#76)
1 parent ce9ec2b commit a32c1c3

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.List;
6+
7+
public class SortTheMatrixDiagonally {
8+
9+
private final int[][] input;
10+
11+
public SortTheMatrixDiagonally(int[][] input) {
12+
this.input = input;
13+
}
14+
15+
public int[][] solution() {
16+
int rows = input.length;
17+
int cols = input[0].length;
18+
List<Integer> diagonals;
19+
for (int r = 0; r < rows; r++) {
20+
int i = r;
21+
int j = 0;
22+
diagonals = new ArrayList<>();
23+
while (i < rows && j < cols) {
24+
diagonals.add(input[i++][j++]);
25+
}
26+
Collections.sort(diagonals);
27+
i = r;
28+
j = 0;
29+
int k = 0;
30+
while (i < rows && j < cols) {
31+
input[i++][j++] = diagonals.get(k++);
32+
}
33+
}
34+
for (int c = 0; c < cols; c++) {
35+
int i = 0;
36+
int j = c;
37+
diagonals = new ArrayList<>();
38+
while (i < rows && j < cols) {
39+
diagonals.add(input[i++][j++]);
40+
}
41+
Collections.sort(diagonals);
42+
i = 0;
43+
j = c;
44+
int k = 0;
45+
while (i < rows && j < cols) {
46+
input[i++][j++] = diagonals.get(k++);
47+
}
48+
}
49+
return input;
50+
}
51+
52+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.smlnskgmail.jaman.leetcodejava.medium;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.assertArrayEquals;
6+
7+
public class SortTheMatrixDiagonallyTest {
8+
9+
@Test
10+
public void defaultTest() {
11+
assertArrayEquals(
12+
new int[][]{{1, 1, 1, 1}, {1, 2, 2, 2}, {1, 2, 3, 3}},
13+
new SortTheMatrixDiagonally(
14+
new int[][]{{3, 3, 1, 1}, {2, 2, 1, 2}, {1, 1, 1, 2}}
15+
).solution()
16+
);
17+
}
18+
19+
}

0 commit comments

Comments
 (0)