本文共 1232 字,大约阅读时间需要 4 分钟。
问题描述
原问题链接:
给定一个二维数组代表一个矩阵。例如:
[ [1,2], [3,4] ]这个矩阵具有2行2列。
给定整数r和c分别代表需要将原矩阵变换为目标矩阵的行数和列数。
例如:r=1,c=4,表示将原2行2列的矩阵变换为1行4列的矩阵。 要求:在从原矩阵向目标矩阵变换时,需要保持原矩阵中行元素的顺序。 (原文描述:The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.)Note:
The height and width of the given matrix is in range [1, 100]. The given r and c are all positive.问题分析
矩阵变换时可以先考虑一个基本问题,例如:原矩阵有2行2列,需要变换的目标矩阵是 1行5列,则不能变换。
换句话说:原矩阵和目标矩阵应该需要相同的元素个数。 这样的话具有一个基本的判断条件存在: 原矩阵行数 * 列数 = 变换后的矩阵的行数 * 列数 否则,就无法变换。如果可以变换,则再进一步考虑变换规律。
算法设计
public int[][] matrixReshape(int[][] nums, int r, int c) { int row = nums.length, col = nums[0].length; int newNum = r*c; int oldNum = row * col; if(newNum!=oldNum) return nums; int[][] ret = new int[r][c]; int ri = 0, ci = 0; for(int i=0;i
测试代码如下:
package com.bean.algorithmbasic;public class MatrixReshapeDemo { public int[][] matrixReshape(int[][] nums, int r, int c) { int row = nums.length, col = nums[0].length; int newNum = r*c; int oldNum = row * col; if(newNum!=oldNum) return nums; int[][] ret = new int[r][c]; int ri = 0, ci = 0; for(int i=0;i
(完)
转载地址:http://kwtdi.baihongyu.com/