问题描述:将一个矩阵按照输入的行列数重新排列,如果不能按照输入的行列数重新排列,返回原矩阵。
思路:没什么好想的,一边遍历一边计算对应位置。
原答案:
public int[][] matrixReshape(int[][] nums, int r, int c) {
int col=nums.length;
int row=0;
if(col==0)
return nums;
else{
row=nums[0].length;
if(row==0)
return nums;
else{
if(col*row!=r*c)
return nums;
else{
int[][] res=new int[r][c];
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
int count=i*c+j+1;
if(count%row==0){
res[i][j]=nums[count/row-1][row-1];
}else{
int newCol=count/row;
res[i][j]=nums[newCol][count-(row*(newCol))-1];
}
}
}
return res;
}
}
}
}
最佳答案:
public int[][] matrixReshape(int[][] nums, int r, int c) {
int[][] res = new int[r][c];
if (nums.length == 0 || r * c != nums.length * nums[0].length)
return nums;
int count = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[0].length; j++) {
res[count / c][count % c] = nums[i][j];
count++;
}
}
return res;
}
比起自己的代码简洁了不是一星半点。写代码时候总喜欢搞些自作聪明的弯弯道道。