Reshape the Matrix

In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.

You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.

The reshaped matrix should 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: mat = [[1,2],[3,4]], r = 1, c = 4
Output: [[1,2,3,4]]
Example 2:


Input: mat = [[1,2],[3,4]], r = 2, c = 4
Output: [[1,2],[3,4]]

思路一: 想到的思路是把数字全部收集起来,然后在新数组中重新赋值。看了题解发现赋值有效率更高的方法。假设 n 为原数组的列,c 为新数组的列,那么有结论第 x 个元素在原数组中的下标为(x/n, x%n),而在新数组的对应下标为(x/c, x%c)

public int[][] matrixReshape(int[][] mat, int r, int c) {
	int size = r * c;
	if (size != mat.length * mat[0].length) return mat;

	int[][] result = new int[r][c];

	List<Integer> values = new ArrayList<>();
	for (int i = 0, matLength = mat.length; i < matLength; i++) {
		int[] ints = mat[i];
		for (int j = 0; j < mat[0].length; j++) {
			values.add(ints[j]);
		}
	}

	int idx = 0;
	for (int i = 0; i < result.length; i++) {
		for (int j = 0; j < result[0].length; j++) {
			result[i][j] = values.get(idx++);
		}
	}

	return result;
}

原文地址:http://www.cnblogs.com/iyiluo/p/16853158.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性