Skip to content

Commit b08b94e

Browse files
refactor 498
1 parent 5d01147 commit b08b94e

File tree

1 file changed

+39
-60
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+39
-60
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,71 +1,50 @@
11
package com.fishercoder.solutions;
22

3-
/**
4-
* 498. Diagonal Traverse
5-
*
6-
* Given a matrix of m x N elements (m rows, N columns), return all elements of the matrix in diagonal order
7-
* as shown in the below image.
8-
9-
Example:
10-
11-
Input:
12-
[
13-
[ 1, 2, 3 ],
14-
[ 4, 5, 6 ],
15-
[ 7, 8, 9 ]
16-
]
17-
Output: [1,2,4,7,5,3,6,8,9]
18-
19-
Note:
20-
21-
The total number of elements of the given matrix will not exceed 10,000.
22-
23-
*/
243
public class _498 {
254

26-
public static class Solutoin1 {
27-
/**
28-
* Reference: https://discuss.leetcode.com/topic/77865/concise-java-solution/2
29-
* Just keep walking the matrix, when hitting the four borders (top, bottom, left or right),
30-
* just directions and keep walking.
31-
*/
32-
public int[] findDiagonalOrder(int[][] matrix) {
5+
public static class Solutoin1 {
6+
/**
7+
* Reference: https://discuss.leetcode.com/topic/77865/concise-java-solution/2
8+
* Just keep walking the matrix, when hitting the four borders (top, bottom, left or right),
9+
* just directions and keep walking.
10+
*/
11+
public int[] findDiagonalOrder(int[][] matrix) {
3312

34-
if (matrix == null || matrix.length == 0) {
35-
return new int[0];
36-
}
37-
int m = matrix.length;
38-
int n = matrix[0].length;
39-
int[] result = new int[m * n];
40-
int d = 1;
41-
int i = 0;
42-
int j = 0;
43-
for (int k = 0; k < m * n; ) {
44-
result[k++] = matrix[i][j];
45-
i -= d;
46-
j += d;
47-
48-
if (i >= m) {
49-
i = m - 1;
50-
j += 2;
51-
d = -d;
52-
}
53-
if (j >= n) {
54-
j = n - 1;
55-
i += 2;
56-
d = -d;
13+
if (matrix == null || matrix.length == 0) {
14+
return new int[0];
5715
}
58-
if (i < 0) {
59-
i = 0;
60-
d = -d;
61-
}
62-
if (j < 0) {
63-
j = 0;
64-
d = -d;
16+
int m = matrix.length;
17+
int n = matrix[0].length;
18+
int[] result = new int[m * n];
19+
int d = 1;
20+
int i = 0;
21+
int j = 0;
22+
for (int k = 0; k < m * n; ) {
23+
result[k++] = matrix[i][j];
24+
i -= d;
25+
j += d;
26+
27+
if (i >= m) {
28+
i = m - 1;
29+
j += 2;
30+
d = -d;
31+
}
32+
if (j >= n) {
33+
j = n - 1;
34+
i += 2;
35+
d = -d;
36+
}
37+
if (i < 0) {
38+
i = 0;
39+
d = -d;
40+
}
41+
if (j < 0) {
42+
j = 0;
43+
d = -d;
44+
}
6545
}
46+
return result;
6647
}
67-
return result;
6848
}
69-
}
7049

7150
}

0 commit comments

Comments
 (0)