(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
}
相关推荐
真上帝的左手37 分钟前
10. 软件设计&架构-Spring Security 7 整合CAS SSO 单点登录
java·spring·架构·sso
Zane19941 小时前
单例线程安全、生产者消费者、死锁:并发面试三连问串讲
java·后端
fpcc2 小时前
ubuntu26环境下的开发环境安装处理
c++·并行编程
云烟成雨TD2 小时前
Micrometer 系列【42】链路追踪:Span 体系 | 核心 API
java·链路追踪·micrometer
Gorway2 小时前
理解 Spring 依赖注入:从构造器注入到集合与条件 Bean
java·后端
LiLiYuan.2 小时前
【字符串常量池】
java·开发语言·面试
Sylvia33.2 小时前
从轮询到推送:足球数据API架构演进与火星数据技术拆解
java·服务器·网络·python·websocket·架构
cfm_29142 小时前
高并发系统缓存全解
java·缓存
Ghost Face...2 小时前
龙芯Docker全流程:安装到离线迁移实战
java·docker·eureka
16月6日-晴3 小时前
Java面向对象进阶—static
java·开发语言