LeetCode(498):对角线遍历 Diagonal Traverse(Java)

2019.11.7 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

逻辑推理题,乍一看不是很难,但是极其容易理错,写对也不容易。

观察发现,对角线端点沿着外围首行和最右列遍历,一共需要遍历times=row+col-1轮(times条对角线)。

在每一次遍历中,计算一次对角线遍历的起始端点位置(x,y)与遍历元素个数(行列取短)num。用direction代表对角线遍历方向,左下为true,反之为false。遍历顺序总是从右上到左下,但当遍历方向为左下时,数组顺序存储;反之逆序存储。


传送门:对角线遍历

Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.

给定一个含有 M x N 个元素的矩阵(M 行,N 列),请以对角线遍历的顺序返回这个矩阵中的所有元素,对角线遍历如下图所示。

示例:
输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
输出:  [1,2,4,7,5,3,6,8,9]


/**
 *
 * Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
 * 给定一个含有 M x N 个元素的矩阵(M 行,N 列),请以对角线遍历的顺序返回这个矩阵中的所有元素,对角线遍历如下图所示。
 *
 */

public class DiagonalTraverse {
    public int[] findDiagonalOrder(int[][] matrix) {
        if(matrix.length == 0){
            return new int[0];
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int[] result = new int[row * col];

        //对角线端点沿着外围首行和最右列遍历,一共需要遍历times=row+col-1轮(times条对角线)
        //direction代表对角线遍历方向,左下为true,反之为false。
        boolean direction = false;
        int times = 0;
        int idx = 0;
        while(times < row + col - 1){
            //位置(x,y)代表对角线遍历的起始端点,num为遍历元素个数(行列取短)
            int x = times < col ? 0 : times - col + 1;
            int y = times < col ? times : col - 1;
            int num = times < col ? Math.min(y + 1, row) : Math.min(row - x, col);
            //遍历顺序总是从右上到左下,但当遍历方向为左下时,数组顺序存储;反之逆序存储。
            int loc = direction ? idx : idx + num - 1;
            while(num-- != 0){
                result[loc] = matrix[x++][y--];
                loc = direction ? loc + 1 : loc - 1;
                idx++;
            }
            direction = !direction;
            times++;
        }
        return result;
    }
}




#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

发布了246 篇原创文章 · 获赞 316 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_20304723/article/details/102951583