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;
}
}