GuoXin Li's Blog

LeetCode566.Reshape the Matrix 重置矩阵

字数统计: 361阅读时长: 2 min
2020/02/23 Share

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:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//java
class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
if (nums.length == 0) return nums;
int m = nums.length;
int n = nums[0].length;
if ( m*n != r*c) return nums;

int[][] arr = new int[r][c];
for (int i = 0; i < m*n; i++){
int cur_r = i/n;
int cur_c = i%n;
int new_r = i/c;
int new_c = i%c;
arr[new_r][new_c] = nums[cur_r][cur_c];
}
return arr;
}
}

Time Complexity: $O(m*n)$

Space Complexity: $O(m*n)$

Note: reshape matrix algrith, mn == nums.length nums[0].length

Optimizing arrange:

1
2
3
4
5
6
7
8
9
10
11
12
13
int m = 0;
int n = 0;
int[][] arr = new int[r][c];
for(int = 0; i < nums.length; i++ ){
for(int j = 0; j < nums[0].length; j++){
arr[m][n] = nums[i][j];
n++;
if(n == c){
m++;
n = 0;
}
}
}
CATALOG
  1. 1. 566. Reshape the Matrix
  2. 2. Example 1:
  3. 3. Explanation:
  4. 4. Example 2: