给你一个大小为 m x n 的矩阵 mat ,请以对角线遍历的顺序,用一个数组返回这个矩阵中的所有元素。
代码思路:以第一行和右边最后一列作为每轮的开始元素,先用temp存储,全部按 从左上到右下 的顺序遍历,但是插入到res[ ]数组时,把奇数轮的temp翻转插入。
class Solution {
public int[] findDiagonalOrder(int[][] mat) {
if(mat == null||mat.length==0){
return new int[0];
}
int N = mat.length;
int M = mat[0].length;
int[] res = new int[N*M];
int k = 0;
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int i = 0;i<M+N-1;i++){
temp.clear();
//确定每轮的开始元素位置
int r = i < M ? 0:i-M+1;
int c = i<M ?i:M-1;
while(r<N&&c>=0){
temp.add(mat[r][c]);//temp存储
r++;//从左上到右下
c--;//从左上到右下
}
//将偶数轮翻转
if(i%2==0){
Collections.reverse(temp);
}
//每轮最后都将temp存储的元素插入,一共M+N轮
for(int j = 0;j<temp.size();j++){
res[k] = temp.get(j);
k++;
}
}
return res;
}
}
这题看了答案才看懂,自己一点思路都没有