当前位置:网站首页>力扣解法汇总498-对角线遍历
力扣解法汇总498-对角线遍历
2022-07-22 08:55:00 【失落夏天】
目录链接:
力扣编程题-解法汇总_分享+记录-CSDN博客
GitHub同步刷题项目:
https://github.com/September26/java-algorithms
原题链接:力扣
描述:
给你一个大小为 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
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/diagonal-traverse
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
* 解题思路: * 设置两个方向,分别是左上和右下。forward==0时代表左上,forward==1时代表右下。 * 以左上查找为例,如果(x+1,y-1)没有超出范围,那么就把这个值加入到数组中,否则,说明该反向查找了。 * 把forward设置为1。
代码:
public class Solution498 {
public int[] findDiagonalOrder(int[][] mat) {
int index = 0;
int forward = 0;//0右上,1左下
int[] result = new int[mat[0].length * mat.length];
int x = 0, y = 0;
while (index < result.length) {
System.out.println("y:" + y + ",x:" + x);
result[index++] = mat[y][x];
if (forward == 0) {
if ((x + 1) < mat[0].length && (y - 1) >= 0) {
x++;
y--;
continue;
}
if ((x + 1) < mat[0].length) {
x++;
} else {
y++;
}
forward = 1;
continue;
}
if ((x - 1) >= 0 && (y + 1) < mat.length) {
x--;
y++;
continue;
}
if (y + 1 < mat.length) {
y++;
} else {
x++;
}
forward = 0;
}
return result;
}
}
边栏推荐
- pm的报警告:“npm WARN config global --global, --local are deprecated
- 计算机网络学习笔记7-TCP编程流程及面试题
- C语言中continue的理解(fishing_1)
- Shallow solution of ZMQ lockless queue
- QT笔记—— QTableWidget 之 拖拽行数 和 移动
- Using pypyodbc in Ubuntu cannot connect to SQL Server
- MySQL修改密码不成功(无效)的解决办法
- SQL设计教学管理库
- 数据湖(十八):Flink与Iceberg整合SQL API操作
- 2021-10-18 burn bare board program with EOP
猜你喜欢
QT notes - drag lines and movement of qtablewidget
Fcntl function
【Rust】我该用什么软件开发 Rust | 常用支持 Rust 的编辑器推荐
QT笔记——QJson
主动降噪耳机排行榜10强,主动降噪耳机十大品牌
云原生(十) | Kubernetes篇之Kubernetes简介
Lesson 12 MySQL high availability component MHA
C # entry series (XXVII) -- Brief Analysis of LINQ
C#入门系列(二十七) -- LINQ简析
如何搭建清晰易懂的数据看板?
随机推荐
QT notes - unpolish() and polish() of QT dynamic attributes
「武汉理工大学 软件工程复习」第一章 | 软件工程概述
【Rust】Rust 语言基础 | 学习语言都应该快速得出印象
Maintenance of gbase8s database constraint mode
SQL设计教学管理库
Gbase8s database set constraints statement
prosody相关概念了解。xmpp,jabber,bosh等
QT笔记——QtXml
QT notes - qjason
第十二讲 MySQL之高可用组件MHA
Internet Download Manager2022试用版(简称 IDM)
Ssl/tls protocol attack detection method based on stream spectrum theory
"Review of software engineering in Wuhan University of technology" Chapter 5 | software architecture
Applet sorted by an element of the structure (fishing_3)
「武汉理工大学 软件工程复习」第三章 | 软件需求
Understanding of continue in C language (fishing_1)
面向5G mMTC的网络切片安全研究
Gbase8s database set collection statement
Fabric.js 居中元素
小程序CMS动态处理数据之内容模型和内容集合的使用