在计算机科学中,数据结构是计算机中存储、组织数据的方式。
正确的数据结构选择可以提高算法的效率。在计算机程序设计的过程中,选择适当的数据结构是一项重要工作。许多大型系统的编写经验显示,程序设计的困难程度与最终成果的质量与表现,取决于是否选择了最适合的数据结构。
566. 重塑矩阵
1 将原矩阵的值按顺序看成是一个一维数组
2 将这个一维数组的值一次填充到一个二维数组里面
3 则根据一维数组的下标k,有这样的公式: i = k/col, j = k%col
4 理解:每一行排满后,就要放到下一行;放到下一行时,则根据前面已经排了多少个,去确定该数是在这行的第几列。
5 在原矩阵计算该一维数组的下标 k = i*col + k
/**
* 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){
if(matSize * matColSize[0] != r*c){
*returnSize = matSize;
*returnColumnSizes = matColSize;
return mat;
}
int** ret = (int **)malloc( sizeof(int*) * r);
*returnSize = r;
*returnColumnSizes = (int *)malloc(sizeof(int)*r);
for(int i = 0;i<r;i++){
ret[i] = (int *)malloc(sizeof(int)*c);
(*returnColumnSizes)[i] = c;
}
for(int i = 0;i<matSize;i++){
for(int j=0;j<matColSize[0];j++){
int count = i*matColSize[0]+j;
ret[count/c][count%c] = mat[i][j];
}
}
return ret;
}
118. 杨辉三角
1 构造二维数组来表示杨辉三角,每行的长度是1 2 3 4 …递增
2 每行的第一位和最后一位为1
3 其余的位是上一行的当前列坐标的前一位和当前列坐标的两个数的和:mat[i][j] = mat[i-1][j-1] + mat][i-1][j];
/**
* 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){
int r = numRows;
int **mat = (int **)malloc( sizeof(int *)*r );
*returnSize = r;
*returnColumnSizes = (int *)malloc(sizeof(int)*r);
for(int i=0;i<r;i++){
mat[i] = (int *)malloc(sizeof(int)*(i+1));
(*returnColumnSizes)[i] = i+1;
}
int c;
for(int i = 0;i<r;i++){
if(i==0 ){
mat[0][0] = 1;
continue;
}
c = (*returnColumnSizes)[i];
mat[i][0] = mat[i][c-1]=1;
for(int j =1;j<c-1;j++){
mat[i][j] = mat[i-1][j-1] + mat[i-1][j];
}
}
return mat;
}