LeetCode 498题
这个代码也写的挺优美的。哈哈
class Solution {
public int[] findDiagonalOrder(int[][] mat) {
int flag = 0;//flag偶数,向上遍历,奇数则向下遍历
int col = mat.length;//行
int row = mat[0].length;//列
int count = 0;//计数,count等于mat的元素个数,则遍历结束
int[] resArr = new int[col*row];
int x = 0;
int y = 0;
while(count < col * row) {
if(flag % 2 == 0) {//向上遍历
if(flag < col) {
x = flag;
y = flag - x;
}else {
x = col - 1;
y = flag - x;
}
for(;x>-1&&x<col&&y>-1&&y<row;) {
resArr[count] = mat[x][y];
x--;
y++;
count++;
}
flag++;
}else {//向下遍历
if(flag < row) {
y = flag;
x = flag - y;
}else {
y = row - 1;
x = flag - y;
}
for(;x>-1&&x<col&&y>-1&&y<row;) {
resArr[count] = mat[x][y];
x++;
y--;
count++;
}
flag++;
}
}
return resArr;
}
}
结果