天天看点

LeetCode566:reshape matrix 解答

写在前面:我已经很久没有建设我的CSDN博客了,最近开始刷LeetCode,打算把我的解题过程记录成博客,既是一种总结,也是一种分享。在此先立个flag,在十一月三十日之前把array类的easy等级的题目都刷完(一共34道),并且都记录在博客中,希望不要让我自己打脸。

-----------------------------------分割线-------------------------------------------

题目

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.

题目大意:在MATLAB中有一个非常实用的函数,叫“reshape”,它能够将矩阵重塑为一个完全保留原始数据但是具有不同形状的矩阵。给你一个二维矩阵,以及目标矩阵的行数r,列数c,要求你重塑该矩阵,重塑之后的矩阵应该具有原来矩阵的所有元素并且具有同样的遍历顺序。如果给定的参数合法并且能够执行重塑,输出重塑之后的矩阵,如果不能,输出原来的矩阵。

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:

The height and width of the given matrix is in range [1, 100].

The given r and c are all positive.

解析

第一种想到的方法肯定是在两个矩阵之间设置一个类似缓存的容器,这个容器易于访问数据(比如只有一行的数组),将原始矩阵的所有元素存放在这个容器中,然后从这个容器中逐个取出元素放到重塑之后的矩阵中。

代码如下:

class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int[] temp=new int[r*c];
        int index=0;
        int [][] result=new int[r][c];
        if((nums.length==0)||(nums.length*nums[0].length!=r*c)){
                return nums;
            }
        for(int i=0;i           

复制

这种方法嘛,简单是简单,不过经验告诉我们,简单的效率总是最低。这个方法会逐个访问所有元素两次,比较费时间,时间复杂度是O(n*n),内存开销也大,要应付应付也算OK。

runtime为8ms

更好的方法

提交之后我看到了更好的方法,就是下面这个,只需要一轮遍历就可以了,在遍历原始矩阵的过程中就把新矩阵的内容设置好了,应该没有比这更合理的方法了,因为毕竟最少也要遍历一遍原始矩阵,难点是当原始矩阵的行和列与目标矩阵不同的时候,以原始矩阵的行列为边界,到达边界便换行读取。

class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
		int h = nums.length;
		int w = nums[0].length;
		if (h * w != r * c || h == r) //如果面积不相等或长宽与原来完全一样
			return nums;
		int[][] res = new int[r][c];
		int j = 0;
		int i = 0;
		for (int y = 0; y < r; y++) {
			for (int x = 0; x < c; x++) {
				res[y][x] = nums[j][i++];
				if (i == w) {       //到达行尾
					j++;            //换行
					i = 0;          //回车
				}
			}
		}
		return res;
	}
}
//MaplePC           

复制

runtime为6ms