566. Reshape the Matrix

LeetCode Reshape the Matrix【Easy】

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 1:

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.

给定一个矩阵,r行、c列值,并且依照给定的行和列对原矩阵行排序,填充为r*n的矩阵,如果不能填充,则。

解决

1.直接可以想到的就是将原矩阵转换为一维数组,然后按照对数组遍历遍历然后赋值到给定的矩阵中。
2.转换中找到原矩阵与新矩阵下标之间的关系,最后找到关系是res[i/c][i%c] = nums[i/col][i%col]。

代码

方式一

    /**
     * 矩阵->一维数组 -> 赋值
     * @param nums
     * @param r
     * @param c
     * @return
     */
    public static int[][] matrixReshape(int[][] nums, int r, int c) {

        int[][] result = new int[r][c];
        int row = nums.length;
        int col = nums[0].length;
        if(r*c!=row*col){
            return nums;
        }
        //二维数组变为一维数组
        int index=0;
        int[] oneArray = new int[row*col];
        for (int[] array : nums) {
            for (int e : array) {
                oneArray[index++]=e;
            }
        }
        //组装矩阵获取
        int index2 = 0;
        for(int i=0;i

方式二

 /**
     * 矩阵 转 矩阵
     * @param nums
     * @param r
     * @param c
     * @return
     */
    public static int[][] matrixReshape(int[][] nums,int r,int c){
        int[][] res = new int[r][c];
        //原数组行、列
        int row = nums.length;
        int col = nums[0].length;
        if(r*c!=row*col){
            return nums;
        }
        for(int i=0;i

你可能感兴趣的:(566. Reshape the Matrix)