1. 题目原址
https://leetcode.com/problems/reshape-the-matrix/
2. 题目描述
3. 题目大意
给定一个二维数组,和一个r和c,分别表示将给定的二维数组转换的行数和列数,即将原来的数组转换为行数为 r,列数为 c 的数组
4. 解题思路
- 先判断数组中的元素是否是 r*c 个元素
- 然后定义一个一维数组
temp[r][c]
, 用来存储二维数组中的元素 - 然后再将一维数组转换为二维数组
5. AC代码
class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int x = nums.length, y = nums[0].length;
int[][] ret = new int[r][c];
int[] temp = new int[x * y];
int index = 0;
if(x * y == r * c) {
for(int i = 0; i < x; i++) {
for(int j = 0; j < y; j++) {
temp[index ++] = nums[i][j];
}
}
index = 0;
for(int i = 0; i < r; i ++) {
for(int j = 0; j < c; j ++) {
ret[i][j] = temp[index ++];
}
}
return ret;
} else
return nums;
}
}