leetcode-566-easy

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

发表评论

您的电子邮箱地址不会被公开。