(LeetCode 每日一题) 498. 对角线遍历 (矩阵、模拟)

题目:498. 对角线遍历

思路:矩阵模拟,时间复杂度0(nm)。
按对角线遍历,而每条对角线都是i+j=k,k的范围为0,n-1+m-1。

C++版本:

cpp 复制代码
class Solution {
public:
    vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
        int n=mat.size(),m=mat[0].size();
        vector<int> ans;
        // i+j=k  -> j=k-i;
        for(int k=0;k<n+m-1;k++){
        	//枚举j的值,那需要求出j可达的最小值和最大值
        	//当i=n-1时,j的值最小,但不能小于0
            int mn=max(k-(n-1),0);
            //当i=0时,j的值最大,但不能大于m-1
            int mx=min(k-0,m-1);
            if(k%2==0){
                for(int j=mn;j<=mx;j++){
                    ans.push_back(mat[k-j][j]);
                }
            }else{
                for(int j=mx;j>=mn;j--){
                    ans.push_back(mat[k-j][j]);
                }
            }
        }
        return ans;
    }
};

JAVA版本:

java 复制代码
class Solution {
    public int[] findDiagonalOrder(int[][] mat) {
        int n=mat.length,m=mat[0].length;
        int[] ans=new int[n*m];
        int idx=0;
        // i+j=k  -> j=k-i;
        for(int k=0;k<n+m-1;k++){
            int mn=Math.max(k-(n-1),0);
            int mx=Math.min(k-0,m-1);
            if(k%2==0){
                for(int j=mn;j<=mx;j++){
                    ans[idx++]=mat[k-j][j];
                }
            }else{
                for(int j=mx;j>=mn;j--){
                    ans[idx++]=mat[k-j][j];
                }
            }
        }
        return ans;
    }
}

GO版本:

go 复制代码
func findDiagonalOrder(mat [][]int) []int {
    n,m:=len(mat),len(mat[0])
    ans:=make([]int,n*m)
    idx:=0
    // i+j=k  -> j=k-i;
    for k:=0;k<n+m-1;k++ {
        mn:=max(k-(n-1),0)
        mx:=min(k-0,m-1)
        if k%2==0 {
            for j:=mn;j<=mx;j++ {
                ans[idx]=mat[k-j][j]
                idx++
            }
        }else{
            for j:=mx;j>=mn;j-- {
                ans[idx]=mat[k-j][j]
                idx++
            }
        }
    }
    return ans
}
相关推荐
木井巳12 分钟前
【动态规划: 线性dp】解码方法
java·算法·leetcode·动态规划·推荐算法
春弦_8 小时前
自用算法整理二
数据结构·算法·图论
缓慢更新8 小时前
审批的加签与会签:多人意见怎么合
android·java·数据库·低代码·rxjava
hetao17338379 小时前
2026-10-22~23 hetao1733837 的刷题记录
c++·算法
yuniko-n9 小时前
【JUC】volatile 非原子性深入解析
java
java_nnnn9 小时前
LeetCode刷题滑动窗口(串联所有单词的子串+最小覆盖的子串)Java
算法·leetcode·职场和发展
sun_weitao9 小时前
极简版 MCP 工具实现方案
java·linux·服务器
王老师青少年编程10 小时前
2025年6月GESP真题及题解(C++三级): 选择题和判断题(题解)
c++·真题·gesp·答案·csp·三级·信奥赛
Navigator_Z10 小时前
LeetCode //C - 1301. Number of Paths with Max Score
c语言·算法·leetcode
金銀銅鐵11 小时前
[Java] 展示增删元素时 LinkedList 的内部变化
java·后端·ai编程