首页 > 其他 > 详细

566. Reshape the Matrix

时间:2017-10-19 18:57:06      阅读:273      评论:0      收藏:0      [点我收藏+]

 

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!