​LeetCode刷题实战566:重塑矩阵

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 重塑矩阵,我们先来看题面:

https://leetcode-cn.com/problems/reshape-the-matrix/

In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.

You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.

The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

在 MATLAB 中,有一个非常有用的函数 reshape ,它可以将一个 m x n 矩阵重塑为另一个大小不同(r x c)的新矩阵,但保留其原始数据。

给你一个由二维数组 mat 表示的 m x n 矩阵,以及两个正整数 r 和 c ,分别表示想要的重构的矩阵的行数和列数。

重构后的矩阵需要将原始矩阵的所有元素以相同的 行遍历顺序 填充。

如果具有给定参数的 reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。

示例                         

b66df6d6a74b083a65365b68dae23c19.png

解题

https://www.jianshu.com/p/780a154cdb63

思路很朴素,首先判断能不能转换,不能转换的话,就直接结束了。

能转换的话就是首先申请一个r维向量。开始还有些想当然,没申请就用,然后测试的时候就越界了。申请了两个 int 变量去记录当前转换到哪一行哪一列了。接下来就一路遍历挨个转换。

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        if (nums.size()*nums[0].size() != r*c) {
            return nums;
        }
        vector<vector<int> > num(r);
        int rl=0, cl=0;
        for (int i = 0; i < nums.size(); ++i) {
            for (int j = 0; j < nums[0].size(); ++j) {
                if (cl < c) {
                    num[rl].push_back(nums[i][j]);
                    cl++;
                } else {
                    cl = 0;rl++;
                    num[rl].push_back(nums[i][j]);
                    cl++;
                }
            }
        }

        return num;
    }
};

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-560题汇总,希望对你有点帮助!

LeetCode刷题实战561:数组拆分 I

LeetCode刷题实战562:矩阵中最长的连续1线段

LeetCode刷题实战563:二叉树的坡度

LeetCode刷题实战564:寻找最近的回文数

LeetCode刷题实战565:数组嵌套

f6059410990ccc628f0a3f3f8cf723bc.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值