LeetCode 498. Diagonal Traverse
原题链接在这里:https://leetcode.com/problems/diagonal-traverse/
题目:
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:
Note:
The total number of elements of the given matrix will not exceed 10,000.
题解:
The result size should be m*n.
For each value, when r + c is even, index in matrix is moving right up. First check if it is hitting right, if yes, move down. Then check if it is hitting up, if yes, move right. Otherwise move right up.
When r + c is odd, index in matrix is moving left down.First check if it is hitting down, if yes, move right. Then check if it is hitting left, if yes, move down. Otherwise move left down.
Think this as when it hit the corner, which direction it would move first.
Time Complexity: O(m*n). m = matrix.length. n = matrix[0].length.
Space: O(1). regardless res.
AC Java:
class Solution { public int[] findDiagonalOrder(int[][] matrix) { if(matrix == null || matrix.length == 0 || matrix[0].length == 0){ return new int[0]; } int m = matrix.length; int n = matrix[0].length; int [] res = new int[m*n]; int r = 0; int c = 0; for(int i = 0; i<m*n; i++){ res[i] = matrix[r][c]; if((r + c) % 2 == 0){ if(c == n-1){ r++; }else if(r == 0){ c++; }else{ r--; c++; } }else{ if(r == m - 1){ c++; }else if(c == 0){ r++; }else{ r++; c--; } } } return res; } }