前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode498. Diagonal Traverse

leetcode498. Diagonal Traverse

作者头像
眯眯眼的猫头鹰
发布2019-07-22 16:27:57
4840
发布2019-07-22 16:27:57
举报

题目要求

代码语言:javascript
复制
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.

 

Example:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

Output:  [1,2,4,7,5,3,6,8,9]
clipboard.png
clipboard.png

思路和代码

其实这道题目不难,只要捋清楚一些边界的场景即可。自上而下遍历数组时,一定是自右往左移动的,因此下标移动的方向为[row, column]=>[row+1, column-1]。自上而下有两种边界场景,一个是到达了左边界,此时的移动方向变为[row, column]=>[row+1, column], 即上图中的4->7。另一个是遇到了下边界,此时的移动方向变为[row, column]=>[row, column+1],即上图中的8->9。同理,自下而上遍历数组时,一定是自左往右移动的,因此下标的移动方向为[row, column]=>[row-1, column+1]。它同样有两个边界场景,一个是到达了右边界,此时的移动方向变为[row, column]=>[row+1, column],还有一个场景是遇到上边界,此时的移动方向变为[row, column]=>[row, column+1]

上述思路的代码如下:

代码语言:javascript
复制
    public int[] findDiagonalOrder(int[][] matrix) {
        if(matrix==null || matrix.length==0 || matrix[0].length==0) return new int[0];
        int row = matrix.length;
        int column = matrix[0].length;
        int[] result = new int[row * column];
        int rowIndex = 0;
        int columnIndex = 0;
        boolean up = true;
        int index = 0;
        while(index < result.length) {
            result[index++] = matrix[rowIndex][columnIndex];
            if(up) {
                if(rowIndex > 0 && columnIndex < column-1) {
                    rowIndex--;
                    columnIndex++;
                }else {
                    up = false;
                    if(columnIndex < column-1){
                        columnIndex++;
                    }else {
                        rowIndex++;
                    }
                }
                    
            }else {
                if(rowIndex < row-1 && columnIndex > 0) {
                    rowIndex++;
                    columnIndex--;
                }else{
                    up = true;
                    if(rowIndex < row-1) {
                        rowIndex++;
                    }else {
                        columnIndex++;
                    }
                }
            }
        }
        return result;
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路和代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档