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"方法,将矩阵转化为一个新的矩阵,并保持原有的数据。


分析及解答

  1. 矩阵转换前提】假设转换前矩阵有m行、n列,而转换之后的矩阵有 r 行 、c 列。能够完成转换的条件是 : m * n == r  * c
  2. 转换公式】因为题目要求,按照原矩阵次序在新矩阵中分配下标,所以新矩阵与原矩阵的下标存在某种映射关系,该部分的目标是找到那种映射关系。
  3. 新旧下标映射】 假设在旧矩阵中某个数的行下标为 i ,列 下标为 j 。我们尝试将旧矩阵拉成一行的数组,数组下标为pos,于是得到 pos = i * n + j ;借助一行的数组,转换到新的矩阵,假设新矩阵中新的行标为 p ,列标 为 q ,于是得到 p = pos / c ; q = pos % c; ( 总体思路见图1)

图1:


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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值