码迷,mamicode.com
首页 > 其他好文 > 详细

566. Reshape the Matrix

时间:2017-10-19 20:00:26      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:diff   atl   different   cti   vector   dimen   previous   param   otherwise   

 

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-traversingorder as they were.

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

1 Input: 
2 nums = 
3 [[1,2],
4  [3,4]]
5 r = 1, c = 4
6 Output: 
7 [[1,2,3,4]]
8 Explanation:
9 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.

 

Solution1:

 1  1 //============================================================================
 2  2 // Name        : Reshape the Matrix.cpp
 3  3 // Author      : xmh
 4  4 // Version     :
 5  5 // Copyright   : Your copyright notice
 6  6 // Description : Hello World in C++, Ansi-style
 7  7 //============================================================================
 8  8 
 9  9 #include <iostream>
10 10 #include <algorithm>
11 11 #include <vector>
12 12 using namespace std;
13 13 
14 14 class Solution {
15 15 public:
16 16     vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c){
17 17         int original_r = nums.size();
18 18         int original_c = num[0].size();
19 19         int n = original_r * original_c;
20 20         if (n == r*c){
21 21             vector<vector<int>> newMatrix(r, <vector<int>(c,0));
22 22             for (int i = 0; i < n; i++)
23 23                 newMatrix[i / c][i % c] = nums[i / original_c][i % original_c];
24 24             return newMatrix;
25 25         }
26 26         else
27 27             return nums;
28 28     }
29 29 
30 30 };
31 31   
32  

 

566. Reshape the Matrix

标签:diff   atl   different   cti   vector   dimen   previous   param   otherwise   

原文地址:http://www.cnblogs.com/xumh/p/7694040.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!