566. Reshape the Matrix

2017-09-21  本文已影响0人  namelessEcho

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.

我使用整个长度来变换访问两个数组的下标,公式是i*col+j+1=count。
但是我在重新映射到result数组时,发生了错误。使用了index1=count/col来访问i。当j=col-1时使用这个公式的话,明显的并不能得到我想要的I,例如对于一个2x2的矩阵,当J=1时明显的count=2,那么count/2=1,但是此时明显的I=0,根源在于我为了计算count对j进行了加一处理,但这个处理在进行得index1操作时会对I有影响

class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int row =nums.length;
        int col =nums[0].length;
        if(r*c!=row*col)
            return nums;
        int[][] result = new int[r][c];
        for(int i = 0 ;i<row;i++)
        {
            for(int j = 0;j<col;j++)
            {
                int count =i*col+j+1;
                int index1=  (count-1)/c ;
                int index2=  (count-1)%c;
                result[index1][index2]=nums[i][j];
            }
        
        }
        return result;
    }
}
上一篇下一篇

猜你喜欢

热点阅读