Leetcode LCP 44. 开幕式焰火

9 篇文章 0 订阅

题目链接

LCP 44. 开幕式焰火

代码

法一利用uthash

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct my_struct {
    int id;                    /* key */
    UT_hash_handle hh;         /* makes this structure hashable */
};
int dfs(struct TreeNode* root, struct my_struct *hash) {
    struct my_struct *tmp;
    int count = 0;
    if (!root) {
        return 0;
    }
    HASH_FIND_INT(hash, &root->val, tmp);
    if (!tmp) {
        count = 1;
        tmp = (struct my_struct *)malloc(sizeof *tmp);
        tmp->id = root->val;
        HASH_ADD_INT(hash, id, tmp);
    }
    return count + dfs(root->left, hash) + dfs(root->right, hash);
}
int numColor(struct TreeNode* root){
    struct my_struct *hash = NULL; // 1
    return dfs(root, hash);
}
  1. struct my_struct *hash = NULL; 不能为全局,也就是放在函数外面,因为力扣可能会利用for循环调用你写的函数,全局变量会有上一次的信息,所以只能手动用memset清除,当然也得新建一个函数

法二哈希表

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int hash[1001];
int dfs(struct TreeNode* root){
    int count = 0;
    if (!root) {
        return 0;
    }
    if (!hash[root->val]) {
        count++;
        hash[root->val] = 1;
    }
    return count + dfs(root->left) + dfs(root->right);
}
int numColor(struct TreeNode* root){
    memset(hash,0,sizeof(hash)); // 1
    return dfs(root);
}
  1. 还是老问题,如果没有memset只会通过第一个测试用例,第二个测试用例因为hash表里有内容,会导致!hash[root->val]为0,跳过if语句直接返回,最终得到0的错误答案。当然把把数组定义在函数内部也可以,但是新建函数就要多一个参数,为了把数组传入子函数
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int dfs(struct TreeNode* root, int hash[]){
    int count = 0;
    if (!root) {
        return 0;
    }
    if (!hash[root->val]) {
        count++;
        hash[root->val] = 1;
    }
    return count + dfs(root->left, hash) + dfs(root->right, hash);
}
int numColor(struct TreeNode* root){
    int hash[1001] = {0}; // 必须初始化为0
    return dfs(root, hash);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值