zoukankan      html  css  js  c++  java
  • LeetCode

    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:

    1. The total number of elements of the given matrix will not exceed 10,000.
    class Solution {
        public int[] findDiagonalOrder(int[][] matrix) {
            boolean up = true;
            if (matrix.length == 0) return new int[0];
            int[] res = new int[matrix.length * matrix[0].length];
            int i = 0;
            int j = 0;
            for (int k = 0; k < matrix.length * matrix[0].length; k++) {
                res[k] = matrix[i][j];
                if (up) {
                    if ((i-1) >= 0 && (j+1) < matrix[0].length) {
                        i--;
                        j++;
                    } else if ((j+1) < matrix[0].length) {
                        j++;
                        up = false;
                    } else if ((i+1) < matrix.length) {
                        i++;
                        up = false;
                    } else break;
                } else {
                    if ((i+1) < matrix.length && (j-1) >= 0) {
                        i++;
                        j--;
                    } else if ((i+1) < matrix.length) {
                        i++;
                        up = true;
                    } else if ((j+1) < matrix[0].length) {
                        j++;
                        up = true;
                    } else break;
                }
            }
            return res;
    
        }
    }
  • 相关阅读:
    关于LockSupport
    Sqrtx
    Text Justification
    Unique Paths II
    N-Queens
    Anagrams
    CSipSimple通话记录分组
    CSipSimple配置系统
    Permutations II 再分析
    CSipSimple的插件结构
  • 原文地址:https://www.cnblogs.com/wxisme/p/9487332.html
Copyright © 2011-2022 走看看