LeetCode Day6【数据结构】重塑矩阵,杨辉三角
566 Reshape the Matrix重塑矩阵
尝试
直接用的arraycopy的方法,但是wrong answer了,代码如下:
class Solution {
public int[][] matrixReshape(int[][] mat, int r, int c) {
int hang = mat.length;
int lie = mat[0].length;
int len = hang * lie;
if (len != r * c) return mat;
int[] m = new int[len];
for (int i = 0; i < len; i++){
System.arraycopy(mat, 0, m, i, len);
}
int[][] ans = new int[r][c];
for (int j = 0; j < len; j++){
System.arraycopy(m, 0, ans, j, len);
}
return ans;
}
}
法一
public static int[][] matrixReshape(int[][] nums, int r, int c) {
int n = nums.length;
int m = nums[0].length;
if (r * c != n * m) return nums;
int[][] ans = new int[r][c];
int newRow = 0, newCol = 0;
for (int row = 0; row < n; row++) {
for (int col = 0; col < m; col++) {
ans[newRow][newCol] = nums[row][col];
if (newCol < c-1) {
newCol++;
}
else {
newRow++;
newCol = 0;
}
}
}
return ans;
}
法二 官方
对于一个行数为 m,列数为 n,行列下标都从 0 开始编号的二维数组,我们可以通过下面的方式,将其中的每个元素 (i, j)映射到整数域内,并且它们按照行优先的顺序一一对应着 [0, mn)中的每一个整数。形象化地来说,我们把这个二维数组「排扁」成了一个一维数组。如果读者对机器学习有一定了解,可以知道这就是flatten 操作。
这样的映射即为:
(i,j)→i×n+j
同样地,我们可以将整数 xx 映射回其在矩阵中的下标,即
i=x / n
j=x % n
其中 /表示整数除法,%表示取模运算。
那么题目需要我们做的事情相当于:
将二维数组nums 映射成一个一维数组;
将这个一维数组映射回 r 行 c 列的二维数组。
我们当然可以直接使用一个一维数组进行过渡,但我们也可以直接从二维数组 nums 得到 r 行 c 列的重塑矩阵:
设 nums 本身为 m 行 n 列,如果 mn != rc,那么二者包含的元素个数不相同,因此无法进行重塑;
否则,对于x∈[0,mn),第 x 个元素在nums 中对应的下标为(x / n,x % n),而在新的重塑矩阵中对应的下标为(x / c,x % c)。我们直接进行赋值即可。
查漏补缺
需要注意一个基础知识:二维数组的行和列怎么表示:
//对于二维数组nums[][]
int n = nums.length;//行长
int m = nums[0].length;//列长
118 Pascal’s Triangle杨辉三角
法一 找规律
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
if (numRows == 0) return res;
res.add(new ArrayList<>(){{add(1);}});
if (numRows == 1) return res;
res.add(new ArrayList<>(){{add(1); add(1);}});
if (numRows == 2) return res;
List<Integer> preRow = res.get(1);
for (int i = 3; i <= numRows; i++) {
List<Integer> list = new ArrayList<>(){{add(1);}};
for (int j = 1; j < i - 1; j++) {
list.add(preRow.get(j) + preRow.get(j - 1));
}
list.add(1);
preRow = list;
res.add(list);
}
return res;
}
}