[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.

重塑矩阵。

在MATLAB中,有一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。

给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重构的矩阵的行数和列数。

重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。

如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reshape-the-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这是一道实现题。因为数据规模不是很大,我先用一个list存储了所有的元素,然后再按照新的矩阵的尺寸逐个把元素放入。

时间O(mn)

空间O(n)

Java实现

 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         // corner case
 6         if (m * n != r * c) {
 7             return nums;
 8         }
 9         // normal case
10         List<Integer> list = new ArrayList<>();
11         for (int i = 0; i < m; i++) {
12             for (int j = 0; j < n; j++) {
13                 list.add(nums[i][j]);
14             }
15         }
16         int[][] res = new int[r][c];
17         int idx = 0;
18         for (int i = 0; i < r; i++) {
19             for (int j = 0; j < c; j++) {
20                 res[i][j] = list.get(idx);
21                 idx++;
22             }
23         }
24         return res;
25     }
26 }

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/14408135.html