每日一题·498.对角线遍历

题目

给你一个大小为 m x n 的矩阵 mat ,请以对角线遍历的顺序,用一个数组返回这个矩阵中的所有元素

示例

 

思路

定义一个新数组保存对角线值

按题目要求,从对角线进行遍历,并保存遍历到的值

需要区分奇偶,因为奇偶遍历的方向不一样

代码

/*
*findDiagonalOrder:给定一个二维数组,对角线输出
int** mat:给定二维数组
int matSize:给定数组的行数
int* matColSize:给定数组的列长int* returnSize:返回值数组的长度
返回值:返回一维数组并记录一个二维数组对角线值
*/
int* findDiagonalOrder(int** mat, int matSize, int* matColSize, int* returnSize)
{
    if(matSize == 0)
    {   
        //矩阵为空,返回0                                
        *returnSize = 0;
        return NULL;
    }
    int len = matSize * (*matColSize);
    *returnSize =len;
    int* returnNums = (int*)malloc(sizeof(int) *len);
    int row =0;
    int col = 0;
    int index =0;
    
    //循环遍历矩阵
    while(index < len)
    {                             
        returnNums[index] = mat[row][col];                                
        if((row + col) % 2 == 0)
        {                                                   //下标和为偶数,向右上遍历
            if(col < (*matColSize)-1)
            {
                col++;
                if(row > 0)                                 
                    row--;
            }
            else 
            {                                         
                row++;
            }
        }
        else
        {                                              //下标和为奇数,向左下遍历
            if(row < matSize-1)
            {
                row++;
                if(col > 0)                                  
                    col--;
            }
            else                                          
                col++;
        }
        index++;
    }

    return returnNums;

}

时间空间复杂度

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值