LeetCode | 566. Reshape the Matrix 简单矩阵循环题

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

You'regiven a matrix represented by a two-dimensional array, and two positive integers r and c representingthe row number andcolumn number of the wanted reshaped matrix, respectively.

Thereshaped matrix need to be filled with all the elements of the original matrixin the same row-traversing order as they were.

Ifthe 'reshape' operation with given parameters is possible and legal, output thenew reshaped matrix; Otherwise, output the original matrix.

Example1:

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.

Example2:

Input:

nums =

[[1,2],

 [3,4]]

r = 2, c = 4

Output:

[[1,2],

 [3,4]]

Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output theoriginal matrix.

Note:

1.      The height and width of the givenmatrix is in range [1, 100].

2.      The given r and c are all positive.

这是一道简单水题,让你将一个矩阵中的所有数字转移到一个r行c列的矩阵中去,r和c是题目给的

直接遍历一遍原来的矩阵就好了,然后把每一个数字取出来,放入目标矩阵中就完成了,这里需要注意的就是在for循环内部不要使用复杂的算术运算,比如对大数使用index/row,或者是index%row,这样会导致程序运行时间的延长

class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
	int x, y;
	x = nums.size();
	y = nums[0].size();
	if (r <= 0 || c <= 0) return nums;
	if (x*y != r*c) return nums;
	vector<vector<int>> result(r, vector<int>(c, 0));

	int indexR = 0,indexC=0;
	for(int i=0;i<x;i++)
		for (int j = 0; j < y; j++)
		{
			result[indexR][indexC] = nums[i][j];

			if (indexC == c - 1)
			{
				indexR++;
				indexC = 0;
			}
			else {
				indexC++;
			}
			
		}
	return result;
}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值