首页 > 其他 > 详细

Diagonal Traverse

时间:2018-08-28 21:36:57      阅读:201      评论:0      收藏:0      [点我收藏+]
Diagonal Traverse

https://www.youtube.com/watch?v=uj65eeIScnQ

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]
Explanation:
?

class Solution {
    public int[] findDiagonalOrder(int[][] matrix) {
        // sanity check 
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return new int[0];
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int[] res = new int[row * col];
        int index = 0;
        int numberOfIterations = row + col - 1;
        
        for(int i = 0; i < numberOfIterations; i++){
            if(i % 2 == 0){
                // i is even
                int x = i < row ? i : row - 1;
                int y = i < row ? 0 : i - row + 1;
                while(x >= 0 && y < col){
                    res[index++] = matrix[x--][y++];
                    // index++;
                    // x++;
                    // y++
                }
            }else{
                // i is oadd
                int x = i < col ? 0 : i - col + 1;
                int y = i < col ? i : col - 1;
                while(x < row && y >= 0){
                    res[index++] = matrix[x++][y--];
                }
            }
        }
        return res;

    }
}

// idea: find the starting points for both directions, 
// these two directions can be categorized as one , right up
// another one is left down, 
// the use of index 

 

Diagonal Traverse

原文:https://www.cnblogs.com/tobeabetterpig/p/9550950.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!