当前位置:网站首页>LeetCode:498. Diagonal traversal

LeetCode:498. Diagonal traversal

2022-07-06 08:50:00 Bertil

Give you a size of m x n Matrix mat , Please traverse diagonally , Use an array to return all the elements in the matrix .

Example 1:
 Insert picture description here

 Input :mat = [[1,2,3],[4,5,6],[7,8,9]]
 Output :[1,2,4,7,5,3,6,8,9]

Example 2:

 Input :mat = [[1,2],[3,4]]
 Output :[1,2,3,4]

Tips :

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 10^4
  • 1 <= m * n <= 10^4
  • -10^5 <= mat[i][j] <= 10^5

Their thinking

1. First traverse the matrix , And then create a new one map To store key and value,key Is the sum of horizontal and vertical coordinates ,value by key An array of equal elements ( That is, an array of elements of each diagonal )
2. Then create a new result array res, Traverse map, Make the diagonal even ( That is to say 2 Diagonals 、 The first 4 Diagonals …, Satisfy key % 2 === 1) The elements of are placed in positive order res in , Make the diagonal an odd number ( That is to say 1 Diagonals 、 The first 3 Diagonals …, Satisfy key % 2 === 0) Put the elements of in reverse order res in , Finally back to res that will do

Code

/** * @param {number[][]} mat * @return {number[]} */
var findDiagonalOrder = function(mat) {
    
    const row = mat.length
    const col = mat[0].length
    const record = new Map()
    for (let i = 0; i < row; i++) {
    
        for (let j = 0; j < col; j++) {
    
            const key = i + j
            if (!record.has(key)) record.set(key, [])
                record.get(key).push(mat[i][j])
            }
        }
    const res = []
    for (const [key, nums] of record.entries()) {
    // entries() Get all key value pairs array :[[key1, value1], [key2, value2]]
        key % 2 === 1 ? res.push(...nums) : res.push(...nums.reverse())
    }
    return res
};
原网站

版权声明
本文为[Bertil]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060844309597.html