当前位置:网站首页>LeetCode:498. 对角线遍历
LeetCode:498. 对角线遍历
2022-07-06 08:44:00 【Bertil】
给你一个大小为 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 <= 10^4
- 1 <= m * n <= 10^4
- -10^5 <= mat[i][j] <= 10^5
解题思路
1.首先遍历矩阵,然后新建一个map来存储key和value,key为横纵坐标之和,value为key相等的元素数组(即每条对角线的元素组成的数组)
2.然后新建一个结果数组res,遍历map,将对角线是偶数(即第2条对角线、第4条对角线…,满足key % 2 === 1)的元素正序放入res中,将对角线是奇数(即第1条对角线、第3条对角线…,满足key % 2 === 0)的元素倒序放入res中,最后返回res即可
代码
/** * @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()获取所有的键值对数组:[[key1, value1], [key2, value2]]
key % 2 === 1 ? res.push(...nums) : res.push(...nums.reverse())
}
return res
};
边栏推荐
- The mysqlbinlog command uses
- LeetCode:673. 最长递增子序列的个数
- 有效提高软件产品质量,就找第三方软件测评机构
- Revit 二次开发 HOF 方式调用transaction
- 如何进行接口测试测?有哪些注意事项?保姆级解读
- C语言双指针——经典题型
- Process of obtaining the electronic version of academic qualifications of xuexin.com
- R language ggplot2 visualization: place the title of the visualization image in the upper left corner of the image (customize Title position in top left of ggplot2 graph)
- Light of domestic games destroyed by cracking
- Sort according to a number in a string in a column of CSV file
猜你喜欢

深度剖析C语言数据在内存中的存储

Charging interface docking tutorial of enterprise and micro service provider platform

Screenshot in win10 system, win+prtsc save location

sublime text中conda环境中plt.show无法弹出显示图片的问题

JVM quick start

Unified ordering background interface product description Chinese garbled

egg. JS project deployment online server

The harm of game unpacking and the importance of resource encryption

sublime text的编写程序时的Tab和空格缩进问题

Generator parameters incoming parameters
随机推荐
Roguelike game into crack the hardest hit areas, how to break the bureau?
What is CSRF (Cross Site Request Forgery)?
Restful API design specification
Function coritization
Problems in loading and saving pytorch trained models
@JsonBackReference和@JsonManagedReference(解决对象中存在双向引用导致的无限递归)
TP-LINK enterprise router PPTP configuration
【Nvidia开发板】常见问题集 (不定时更新)
Computer cleaning, deleted system files
Variable length parameter
[embedded] print log using JLINK RTT
The harm of game unpacking and the importance of resource encryption
China high purity silver nitrate Market Research and investment strategy report (2022 Edition)
Trying to use is on a network resource that is unavailable
延迟初始化和密封类
Browser thread
企微服务商平台收费接口对接教程
gcc动态库fPIC和fpic编译选项差异介绍
角色动画(Character Animation)的现状与趋势
Screenshot in win10 system, win+prtsc save location