leecode刷题笔记Day1

树的层次遍历:
可以利用队列来实现。先将根结点入队,再依次出队,将出队结点的子结点入队,以此类推。
例题:

先贴上解答:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* levelOrder(struct TreeNode* root, int* returnSize){
    int Maxsize=10000;
    struct TreeNode* node[Maxsize];
    int *returned=(int*)calloc(Maxsize, sizeof(int));
    int i=0,j=0;
    memset(node, 0, sizeof(struct TreeNode*)*Maxsize);
    node[i]=root;
    *returnSize=0;
    for(i;node[i]!=NULL;i++)
    {
        returned[i]=node[i]->val;
        (*returnSize)++;
        if(node[i]->left)   node[++j]=node[i]->left;
        if(node[i]->right)   node[++j]=node[i]->right;
    }
    return returned;
}

有几个参考了解答后学习到的点:
C 库函数 - calloc() 来自于C 标准库 -
C 库函数 void *calloc(size_t nitems, size_t size) 分配所需的内存空间,并返回一个指向它的指针。malloc 和 calloc 之间的不同点是,malloc 不会设置内存为零,而 calloc 会设置分配的内存为零。

void *calloc(size_t nitems, size_t size)

其中
nitems -- 要被分配的元素个数。
size -- 元素的大小。

指针指示的的内容更新踩坑
初始化时,returnSize=0;将returnSize指针指示的地址的值改为了0,但更新该值时,若采用returnSize++,并不能将其更改为1,须采用(*returnSize)++

递归与动态规划

int cache[101] = {0};
int fib(int n){
    if (0 == n || 1 == n)
        return n;
    if (0 != cache[n])
        return cache[n];
    cache[n] = (fib(n - 1) + fib(n - 2)) % 1000000007;
    return cache[n];
}

单纯递归会超时,递归过程会有重复计算,

eg. 
f(3)=f(2)+f(1)
f(4)=f(3)+f(2)
f(2)就被重复计算

斐波那契数列题解摘自
作者:archiewyq
链接:https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof/solution/di-gui-chao-shi-chu-li-by-archiewyq-agk8/
来源:力扣(LeetCode)

int类型的取值范围
上图列出了int类型的值,在16位平台下最有符号int最大为32767(2^15-1),在32位及以上平台,有符号int最大为2147483647(2^31-1),二者的最前一位用于表示符号正负。因此题干中的1000000007在此范围内,可以直接存入int。

发表评论

您的电子邮箱地址不会被公开。