0
点赞
收藏
分享

微信扫一扫

LeetCode 498题

半夜放水 2022-01-26 阅读 17

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;
    }
}

结果
在这里插入图片描述

举报

相关推荐

0 条评论