public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
ArrayList<Integer> li=new ArrayList<Integer>();
int i=0,j=0,count=0;
if((nums.length*nums[0].length)!=(r*c))return nums;
for(;i<nums.length;i++){
for(j=0;j<nums[0].length;j++){
li.add(nums[i][j]);
}
}
int[][] res=new int[r][c];
for(i=0;i<r;i++){
for(j=0;j<c;j++){
res[i][j]=li.get(count++);
}
}
return res;
}
}
太蠢了,人家只用一次循环就搞定了。
public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int row = nums.length;
int col = nums[0].length;
int [][] result = new int[r][c];
if (r*c!=row*col){
return nums;
}
int n=0, m=0;
for (int i=0; i<row; i++){
for (int j=0; j<col; j++){
result[n][m]=nums[i][j];
m++;
if (m==c){
m=0;
n++;
}
}
}
return result;
}
}