import java.util.Arrays;
/**
* @author xnl
* @Description:
* @date: 2022/6/14 21:09
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
// int[][] mat = {{1,2,3},{4,5,6},{7,8,9}};
// int[][] mat = {{2, 3}};
int[][] mat = {{3}, {2}};
System.out.println(Arrays.toString(solution.findDiagonalOrder(mat)));
}
/**
* @param mat
* @return
*/
public int[] findDiagonalOrder(int[][] mat) {
if (mat.length == 1){
return mat[0];
}
int m = mat.length;
int n = mat[0].length;
// 一共有的边
int edge = m + n - 1;
int[] ans = new int[m * n];
int index = 0;
for (int i = 0; i < edge; i++){
// 奇数代表从上到下,偶数代表从下到上
if (i % 2 == 1){
int x = i < n ? 0 : i - n + 1;
int y = i < n ? i : n - 1;
while (x < m && y >= 0){
ans[index] = mat[x][y];
index++;
x++;
y--;
}
} else {
int x = i < m ? i : m - 1;
int y = i < m ? 0 : i - m + 1;
while (x >= 0 && y < n){
ans[index] = mat[x][y];
index++;
x--;
y++;
}
}
}
return ans;
}
}
力扣:498. 对角线遍历
最新推荐文章于 2024-08-25 02:40:51 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)