Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[2022-06-14]498. 对角线遍历👋数组👋矩阵👋模拟 #61

Open
webVueBlog opened this issue Jun 14, 2022 · 1 comment
Open

Comments

@webVueBlog
Copy link
Collaborator

题目链接: https://leetcode-cn.com/problems/diagonal-traverse

难度: Medium
标签: 数组 矩阵 模拟

@dreamjean
Copy link
Collaborator

498. 对角线遍历

Description

Difficulty: 中等

Related Topics: 数组, 矩阵, 模拟

给你一个大小为 m x n 的矩阵 mat ,请以对角线遍历的顺序,用一个数组返回这个矩阵中的所有元素。

示例 1:

输入:mat = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,4,7,5,3,6,8,9]

示例 2:

输入:mat = [[1,2],[3,4]]
输出:[1,2,3,4]

提示:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 104
  • 1 <= m * n <= 104
  • -105 <= mat[i][j] <= 105

Solution

思路:

  • 每个对角线的和 i + j 相同
  • 仔细观察可以发现,i + j 每次增加的是1
  • 因此可以以二维数组的方式,以 i + j 为下标,把相同的对角线的数存进对应的下标数组中
  • 将二维数组转为一维数组,偶数下标的子数组需要先进行反转

Language: JavaScript

/**
 * @param {number[][]} mat
 * @return {number[]}
 */
var findDiagonalOrder = function(mat) {
    const [m, n] = [mat.length, mat[0].length];
    const nums = [];

    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            (i + j) in nums ? nums[i + j].push(mat[i][j]) : nums[i + j] = [mat[i][j]];
        }
    }
    
    return nums.reduce((arr, curr, i) => {
        !(i % 2) ? arr.push(...curr.reverse()) : arr.push(...curr);
        return arr;
    }, [])
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants