当前位置:网站首页>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
};
边栏推荐
- How to conduct interface test? What are the precautions? Nanny level interpretation
- Colorlog combined with logging to print colored logs
- TDengine 社区问题双周精选 | 第三期
- Problems in loading and saving pytorch trained models
- Introduction to the differences between compiler options of GCC dynamic library FPIC and FPIC
- 【ROS】usb_cam相机标定
- vb.net 随窗口改变,缩放控件大小以及保持相对位置
- [embedded] print log using JLINK RTT
- Research and investment forecast report of citronellol industry in China (2022 Edition)
- MySQL learning records 12jdbc operation transactions
猜你喜欢
vb.net 随窗口改变,缩放控件大小以及保持相对位置
C language double pointer -- classic question type
角色动画(Character Animation)的现状与趋势
Navicat premium create MySQL create stored procedure
Unified ordering background interface product description Chinese garbled
[MySQL] lock
Indentation of tabs and spaces when writing programs for sublime text
C语言双指针——经典题型
C语言深度解剖——C语言关键字
Simple use of promise in uniapp
随机推荐
Crash problem of Chrome browser
Trying to use is on a network resource that is unavailable
Purpose of computer F1-F12
Current situation and trend of character animation
Chrome浏览器的crash问题
有效提高软件产品质量,就找第三方软件测评机构
深度剖析C语言数据在内存中的存储
角色动画(Character Animation)的现状与趋势
JS pure function
MySQL learning record 10getting started with JDBC
Sublime text using ctrl+b to run another program without closing other runs
按位逻辑运算符
Analysis of the source code of cocos2d-x for mobile game security (mobile game reverse and protection)
Deep analysis of C language data storage in memory
TDengine 社区问题双周精选 | 第三期
POI add write excel file
Unsupported operation exception
egg. JS project deployment online server
Screenshot in win10 system, win+prtsc save location
Problems in loading and saving pytorch trained models