[LeetCode] 566. Reshape the Matrix

2207 ワード

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.

  • タイトル:2次元配列と2つの正の整数rとcを入力し、MATLABにおける行列のreshape法を実現し、行数r、列数nの新しい行列(配列)を返す.入力したrとcが不正なパラメータである場合、元のマトリクス(配列)が返されます.
    実現構想:元の行列の行数がrows、列数がcolsであると仮定し、元の行列と新しい行列は同じ要素数を保証しなければならないため、rとcの合法的な条件はr*c=rows*colsである.以下に議論する行列は、行と列が0からカウントされる.reshapeは行優先の順序で行われるため、元の行列の各行を並べて(1行しかない行列に引き伸ばす)配置することが想像できる.このとき、元の行列のi行目j列目の要素は、並べて行列のi*cols+j番目の要素であり、N=i*cols+jとなる.この要素を新しい行列のp行目q列に配置すべきであると仮定すると,並列行列の理屈からp*c+q=Nが分かるので,p=N/c,q=N%cがある.
    class Solution {
        public int[][] matrixReshape(int[][] nums, int r, int c) {
            if (nums == null) throw new IllegalArgumentException("argument is null");
            int rows = nums.length, cols = rows == 0 ? 0 : nums[0].length;
            if (r * c != rows * cols) return nums;
            int[][] result = new int[r][c];
            for (int count = 0; count < rows * cols; count++)
                result[count / c][count % c] = nums[count / cols][count % cols];
            return result;
        }
    }