zoukankan      html  css  js  c++  java
  • 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:

     1 class Solution {
     2     public int[] findDiagonalOrder(int[][] matrix) {
     3         if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
     4             return new int[0];
     5         }
     6         
     7         int m = matrix.length;
     8         int n = matrix[0].length;
     9         int [] res = new int[m*n];
    10         int r = 0;
    11         int c = 0;
    12         for(int i = 0; i<m*n; i++){
    13             res[i] = matrix[r][c];
    14             
    15             if((r + c) % 2 == 0){
    16                 if(c == n-1){
    17                     r++;
    18                 }else if(r == 0){
    19                     c++;
    20                 }else{
    21                     r--;
    22                     c++;
    23                 }
    24             }else{
    25                 if(r == m - 1){
    26                     c++;
    27                 }else if(c == 0){
    28                     r++;
    29                 }else{
    30                     r++;
    31                     c--;
    32                 }
    33             }
    34         }
    35         
    36         return res;
    37     }
    38 }

    类似Spiral Matrix.

  • 相关阅读:
    杭电 1521 排列组合

    杭电 1799 循环多少次?
    杭电1028 Ignatius and the Princess III(整数拆分)
    毕业论文A.1 Matlab环境配置
    Open Graphics Library初步_搭建环境_GLUT
    Open Graphics Library初步_摄影机_GLUT
    C#使用office相关com组件
    插入排序
    二叉树的四种遍历方法(递归、迭代)
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12015933.html
Copyright © 2011-2022 走看看