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.

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

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.

 Idea 1. Observe and find the 1-D index is: rowIndex * N + columnIndex,

Time complexity: O(M*N)

Space complexity: O(1)

 1 class Solution {
 2     public int[][] matrixReshape(int[][] nums, int r, int c) {
 3         int M = nums.length;
 4         int N = nums[0].length;
 5         
 6         if(M*N != r*c || M == r) {
 7             return nums;
 8         }
 9         
10         int[][] result = new int[r][c];
11         for(int i = 0; i < M; ++i) {
12             for(int j = 0; j < N; ++j) {
13                 int x = (i * N + j)/c;
14                 int y = (i * N + j)%c;
15                 result[x][y] = nums[i][j];
16             }
17         }
18         
19         return result;
20     }
21 }

Idea 1.b one-loop instead, more conciser code

 1 class Solution {
 2     public int[][] matrixReshape(int[][] nums, int r, int c) {
 3         int M = nums.length;
 4         int N = nums[0].length;
 5         
 6         if(M*N != r*c || M == r) {
 7             return nums;
 8         }
 9         
10         int[][] result = new int[r][c];
11         for(int i = 0; i < M * N; ++i) {
12             result[i/c][i%c] = nums[i/N][i%N];
13         }
14         
15         return result;
16     }
17 }

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄