每日小细节新增算法好题合集,现在是初阶,每天会更新至少两道题目,感兴趣的小伙伴赶紧关注收藏不迷路哦
花费几分钟就能积累一种新的解题思路多是一件美事啊~
1.重塑矩阵
这道题用C最难的是理解很多的参数到底什么意思,题目本身理解起来不是很难
是这样的过程,大家还是具体看我代码里面的注释,这里就不赘述
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** matrixReshape(int** mat, int matSize, int* matColSize, int r, int c, int* returnSize, int** returnColumnSizes){
int m=matSize;//原来数组的行数
int n=matColSize[0]; //用一个数组储存每一行的列数,这里的n就代表整个矩阵的列
if(m*n!=r*c)
{
*returnSize=m;
*returnColumnSizes=matColSize;
return mat;
}
*returnSize=r;
*returnColumnSizes=malloc(sizeof(int )* r); //要返回的列数,解引用之后元素个数就是行数,因为原来保存的是每行的列数
int** ans=(int**)malloc(sizeof(int*)*r);//最终的数组,李阿敏元素是每一行首元素地址,所以数据个数也是行数
for(int i=0;i<r;i++) //先完善新的二维数组到底是几行几列怎么组成新数组的
{
(*returnColumnSizes)[i]=c; //每一行的列数写在要返回值里面
ans[i]=malloc(sizeof(int)*c); //完善新数组每一行到底有几列
}
for(int i=0;i<m*n;i++) //开始导入数据
{
ans[i/c][i%c]=mat[i/n][i%n];
}
return ans;
}
2.杨辉三角
其实杨辉三角很早之前我就写过一篇博客,而且还铺垫了两个例题
但是当时学的比较浅,还在C的前中期,所以实现的比较挫
今天再看这个题,尤其是在前面一题的铺垫下太简单~
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** generate(int numRows, int* returnSize, int** returnColumnSizes){
*returnColumnSizes=(int*)malloc(sizeof(int)*numRows);
*returnSize=numRows;
int**ans=malloc(sizeof(int*)*numRows);
for(int i=0;i<numRows;i++)
{
(*returnColumnSizes)[i]=i+1;
ans[i]=malloc(sizeof(int)*(i+1));
ans[i][0] = 1;
ans[i][i] = 1; //将每行的第一个和最后一个赋值为1
for (int j = 1; j < i; j++)
{
ans[i][j] = ans[i - 1][j] + ans[i - 1][j-1];
}
}
return ans;
}
博主现在是按照力扣的数据结构初阶的题单开始刷,每日都有几道题,我都会准时更新在博客里,欢迎大家一起讨论优化
而且力扣这个系列的题目,每天都是很相似的题,如果第一道不会做看完题解之后正好可以用后一道巩固,省去自己找题的麻烦,推荐!