Leetcode brushing questions---array---reshape the array

In MATLAB, there is a very useful function reshape, which can reshape a matrix into another new matrix with a different size, but retain its original data.

Given a matrix represented by a two-dimensional array, and two positive integers r and c, which respectively represent the number of rows and columns of the desired reconstructed matrix.

The reconstructed matrix needs to fill all the elements of the original matrix in the same row traversal order.

If the reshape operation with the given parameters is feasible and reasonable, output the new reshape 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 result of row traversal nums is [1,2, 3,4]. The new matrix is ​​a 1 * 4 matrix, fill the new matrix line by line with the previous element values.

Example 2:

Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to convert a 2 * 2 matrix into 2 * 4 matrix. So output the original matrix.

note:

给定矩阵的宽和高范围在 [1, 100]。
给定的 r 和 c 都是正数。

Direct violence solution is enough

class Solution {
    
    
    public int[][] matrixReshape(int[][] nums, int r, int c) {
    
    
      int chang =nums.length;int kuang =nums[0].length;int index=0;
      if(r*c!=chang*kuang)return nums;
      int[][] ans=new int[r][c];
      for(int i=0;i<r;i++){
    
    
          for(int j=0;j<c;j++){
    
    
              ans[i][j]=nums[index/kuang][index%kuang];
              index++;
          }
      }
      return ans;
    }
}

Here index/kuang refers to the row number, and index%kuang refers to the column number.
This is because the two-dimensional array is also a one-dimensional sequence when it is stored, and it can be traversed with a variable

If you find it difficult to understand, you can actually complete this part of the content through judgment

       int rows = 0, cols = 0;
        for (int i = 0; i < nums.length; i++) {
    
    
            for (int j = 0; j < nums[0].length; j++) {
    
    
                res[rows][cols] = nums[i][j];
                cols++;
                if (cols == c) {
    
    
                    rows++;
                    cols = 0;
                }
            }
        }
        return res;

作者:LeetCode
链接:https://leetcode-cn.com/problems/reshape-the-matrix/solution/zhong-su-ju-zhen-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

The effect is the same

Source: LeetCode (LeetCode) Link: https://leetcode-cn.com/problems/reshape-the-matrix
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/weixin_46428711/article/details/110482410