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.
我使用整個(gè)長(zhǎng)度來(lái)變換訪問兩個(gè)數(shù)組的下標(biāo)孤澎,公式是i*col+j+1=count。
但是我在重新映射到result數(shù)組時(shí),發(fā)生了錯(cuò)誤襟雷。使用了index1=count/col來(lái)訪問i晾捏。當(dāng)j=col-1時(shí)使用這個(gè)公式的話店茶,明顯的并不能得到我想要的I鲫咽,例如對(duì)于一個(gè)2x2的矩陣,當(dāng)J=1時(shí)明顯的count=2肚豺,那么count/2=1,但是此時(shí)明顯的I=0溃斋,根源在于我為了計(jì)算count對(duì)j進(jìn)行了加一處理,但這個(gè)處理在進(jìn)行得index1操作時(shí)會(huì)對(duì)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;
}
}