前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-566-Reshape the Matrix

leetcode-566-Reshape the Matrix

作者头像
chenjx85
发布2018-05-22 16:29:19
4570
发布2018-05-22 16:29:19
举报

题目描述:

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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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中的每一个元素在新vector中的位置,放进去。

思路清晰,我们可以构造如下代码:

代码语言:javascript
复制
    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;
    }

上述代码实测40ms,beats 82.30% of cpp submissions。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-05-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档