码迷,mamicode.com
首页 > 其他好文 > 详细

Diagonal Traverse

时间:2018-08-28 21:57:49      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:res   fit   while   --   watch   turn   input   lan   new   

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

标签:res   fit   while   --   watch   turn   input   lan   new   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!