LeetCode | 566. Reshape the Matrix


题目:

In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.

You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to 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.


例子:

Input: 
nums = 
[[1,2],
 [3,4]]
r = 1, c = 4
Output: 
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.


题意:大意就是要求将输入的矩阵变换为指定尺寸的形式,要求初始矩阵的长宽乘row * col == r * c;若不满足以上要求则返回原数组。


思路分析:

因为难度是Easy,所以思路比较简单,数据范围的提示也很小,所以直接做即可。首先对输入矩阵尺寸进行判断,如果符合要求则变换坐标。一次AC,^___________________^*


代码:运行时间39ms

	vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        vector<vector<int>> res;
        int row = nums.size();
        if(row < 1)
            return res;
        int col = nums[0].size();
        if(col < 1)
            return res;
        if(row * col != r * c){
            res = nums;
            return res;
        }
		res = vector<vector<int>>(r, vector<int>(c));
		for(int i = 0; i<r*c; i++){
			int idx1 = i/col, idy1 = i%col;
			int idx2 = i/c, idy2 = i%c;
			res[idx2][idy2] = nums[idx1][idy1];
		}

		return res;
    }


最近Leet上面出了很多新题,哈哈哈加油AC~


题外话:Ode to Joy 2启程啦!哈哈哈哈忍不住偷看了两眼!加油!






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值