Skip to content

Commit b3cc7e2

Browse files
committedMar 3, 2025
Add solution #498
1 parent 7af376d commit b3cc7e2

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,7 @@
399399
495|[Teemo Attacking](./0495-teemo-attacking.js)|Easy|
400400
496|[Next Greater Element I](./0496-next-greater-element-i.js)|Easy|
401401
497|[Random Point in Non-overlapping Rectangles](./0497-random-point-in-non-overlapping-rectangles.js)|Medium|
402+
498|[Diagonal Traverse](./0498-diagonal-traverse.js)|Medium|
402403
500|[Keyboard Row](./0500-keyboard-row.js)|Easy|
403404
501|[Find Mode in Binary Search Tree](./0501-find-mode-in-binary-search-tree.js)|Easy|
404405
502|[IPO](./0502-ipo.js)|Hard|

‎solutions/0498-diagonal-traverse.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 498. Diagonal Traverse
3+
* https://leetcode.com/problems/diagonal-traverse/
4+
* Difficulty: Medium
5+
*
6+
* Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.
7+
*/
8+
9+
/**
10+
* @param {number[][]} mat
11+
* @return {number[]}
12+
*/
13+
var findDiagonalOrder = function(mat) {
14+
const result = new Array(mat.length * mat[0].length);
15+
16+
for (let r = 0, c = 0, d = 1, i = 0; i < mat.length * mat[0].length;) {
17+
result[i++] = mat[r][c];
18+
19+
if (d === 1) {
20+
if (c === mat[0].length - 1) {
21+
r++;
22+
d = -1;
23+
} else if (r === 0) {
24+
c++;
25+
d = -1;
26+
} else {
27+
r--;
28+
c++;
29+
}
30+
} else {
31+
if (r === mat.length - 1) {
32+
c++;
33+
d = 1;
34+
} else if (c === 0) {
35+
r++;
36+
d = 1;
37+
} else {
38+
r++;
39+
c--;
40+
}
41+
}
42+
}
43+
44+
return result;
45+
};

0 commit comments

Comments
 (0)
Please sign in to comment.