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.

Example 1:

```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.```

Example 2:

```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 the original matrix.```

Note:

1. The height and width of the given matrix is in range [1, 100].
2. The given r and c are all positive.

要完成的函数：

vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c)

说明：

1、这道题就是让我们实现matlab中的reshape函数。给定一个二维的vector，以及转换之后矩阵的行数和列数。如果由于给定的行数和列数的原因而不能转换，那么返回原vector。如果可以，那么返回转换之后的vector。

2、首先我们由给定vector得到原行数和原列数，如果它们的积不等于新行数和新列数的积，那么返回原本vector。

```    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c)
{
int orow=nums.size();//初始的行数和列数
int ocol=nums[0].size();
if(orow*ocol!=r*c)
return nums;
vector<int> resc(c);
vector<vector<int>>res(r,resc);
int tr,tc,index;//转换后的行数和列数
for(int i=0;i<orow;i++)
{
for(int j=0;j<ocol;j++)
{
index=i*ocol+j;
tr=index/c;
tc=index%c;
res[tr][tc]=nums[i][j];
}
}
return res;
}```

0 条评论

相关文章

2174

1012. 变换密码

1012. 变换密码 (Standard IO) 时间限制: 1000 ms  空间限制: 262144 KB  具体限制  题目描述 一密码变换规则如下：一...

3014

习题4：变量和命名

"_"下划线这个符号在变量里通常被用作假象的空格，用来隔开单词，切记千万不要用"-"这个符号来连接单词

572

Leetcode 218. The Skyline Problem 线段树

A city's skyline is the outer contour of the silhouette formed by all the build...

3179

Python数据分析(2)-pandas数据结构操作

pandas是一个提供快速、灵活、表达力强的数据结构的Python库，适合处理‘有关系’或者‘有标签’的数据。在利用Python做数据分析的时候，pandas是...

26110

3515

1752

1574

29710

对vector等STL标准容器进行排序操作

STL几乎封装了所有的数据结构中的算法，从链表到队列，从向量到堆栈，对hash到二叉树，从搜索到排序，从增加到删除......可以说，如果你理解了STL，你会...

2582