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.

 


 

题目标签:Array

  这道题目给了我们一个matrix 2d array, 让我们根据给的r 和 c 来重新塑造一个新的矩阵。那么首先我们先判断一下,给的r 和 c 能不能用来塑造一个2d array。比较一下总数就可以了。接下来我们就重塑一个2d array 根据给的r 和c,遍历原来的nums, 设两个int,col 和 row, 对于旧的nums 2d array,当我们每次遍历一行里的每一个数字,我们每次col++,意思就是增加列。一旦当我们自己数的col 列 = c 给的列的时候,我们就更新col 列 = 0, 并且row++。 每一次的数字利用自己计数的row 和 col 代入, res[row][col]。

 

Java Solution:

Runtime beats 38.21% 

完成日期:05/10/2017

关键词:Array

关键点:自己来计数row and column, 并存入每一个int到新的2d array里面

 

 

 1 public class Solution 
 2 {
 3     public int[][] matrixReshape(int[][] nums, int r, int c) 
 4     {
 5         // check if new array is possible.
 6         if(nums.length * nums[0].length != r * c)
 7             return nums;
 8         
 9         int[][] res = new int[r][c];
10         
11         int col=0;
12         int row=0;
13         for(int i=0; i<nums.length; i++)
14         {
15             for(int j=0; j<nums[i].length; j++)
16             {
17                 if(col == c)
18                 {
19                     col = 0;
20                     row++;
21                 }
22                 res[row][col] = nums[i][j];
23                 col++;
24             }
25             
26         }
27         
28         return res;
29     }
30 }

参考资料:N/A

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

posted @ 2017-07-04 06:42  Jimmy_Cheng  阅读(633)  评论(0编辑  收藏  举报