LeetCode 566——Reshape the Matrix

版权声明:欢迎评论和转载,转载时请注明作者和出处,共同维护良好的版权和知识产权秩序。 https://blog.csdn.net/CrazyOnes/article/details/88062535

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

算是一道简单题,千万别被正确率给唬住。

题干说了很多,大概就是对二维矩阵进行一个变维,要求元素不变的情况下,保证输入矩阵和输出矩阵按行读取的顺序是一样的。

如果变维的要求不符合规则,就返回输入矩阵。

那么什么时候变维的要求不符合规则呢,就是新的矩阵元素个数和原矩阵的元素个数不相等。二维矩阵的元素个数也就是行数×列数。

所以题目的思路也就很清晰,首先要判断输出矩阵和输入矩阵的元素个数,然后再构建输出矩阵并返回就可以了。

官网的Solution里三个答案的思路也是基本相同,时间复杂度为O(M * N),空间复杂度为O(M * N).


AC代码:

class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int rl = nums.length;
        int cl = nums[0].length;

        if (rl * cl != r * c) {
            return nums;
        }

        int[][] result = new int[r][c];
        int x = 0, y = 0;
        for (int i = 0; i < rl; ++i) {
            for (int j = 0; j < cl; ++j) {
                if (x >= c) {
                    x = 0;
                    ++y;
                }
                result[y][x] = nums[i][j];
                ++x;
            }
        }

        return result;
    }
}

如有错误,欢迎指摘。也欢迎通过左上角的“向TA提问”按钮问我问题,我将竭力解答你的疑惑。

猜你喜欢

转载自blog.csdn.net/CrazyOnes/article/details/88062535