杭集手工活外发加工网,怀来网站seo,网站建设 语言,app优化排名给你一个大小为 m x n 的矩阵 mat #xff0c;请以对角线遍历的顺序#xff0c;用一个数组返回这个矩阵中的所有元素。
代码思路#xff1a;以第一行和右边最后一列作为每轮的开始元素#xff0c;先用temp存储#xff0c;全部按 从左上到右下 的顺序遍历#xff0c;但是…给你一个大小为 m x n 的矩阵 mat 请以对角线遍历的顺序用一个数组返回这个矩阵中的所有元素。
代码思路以第一行和右边最后一列作为每轮的开始元素先用temp存储全部按 从左上到右下 的顺序遍历但是插入到res[ ]数组时把奇数轮的temp翻转插入。
class Solution {public int[] findDiagonalOrder(int[][] mat) {if(mat null||mat.length0){return new int[0];}int N mat.length;int M mat[0].length;int[] res new int[N*M];int k 0;ArrayListInteger temp new ArrayListInteger();for(int i 0;iMN-1;i){temp.clear();//确定每轮的开始元素位置int r i M ? 0:i-M1;int c iM ?i:M-1;while(rNc0){temp.add(mat[r][c]);//temp存储r;//从左上到右下c--;//从左上到右下}//将偶数轮翻转if(i%20){Collections.reverse(temp);}//每轮最后都将temp存储的元素插入一共MN轮for(int j 0;jtemp.size();j){res[k] temp.get(j);k;}} return res;}
}这题看了答案才看懂自己一点思路都没有