【C语言刷力扣】1748.唯一元素的和

题目:

【C语言刷力扣】1748.唯一元素的和

法一 解题思路:

        由于 nums.length 小于100,新建数组 num[101],用来遍历存放 nums[i]出现的次数。

int sumOfUnique(int* nums, int numsSize) {
    int result = 0;
    int num[101] = {0};  // memset(num, 0, sizof(num));
    for (int i = 0; i < numsSize; i++) {
        num[nums[i]]++;
    }

    for (int i = 0; i < 101; i++) {
        if (num[i] == 1) result += i;
    }
    return result;
}

法二 哈希表(官方)解题思路:

typedef struct {
    int key;
    int val;
    UT_hash_handle hh;
}hashEntry;

int sumOfUnique(int* nums, int numsSize) {
    hashEntry * cnt = NULL;
    int ans = 0;
    for (int i = 0; i < numsSize; ++i) {
        hashEntry * qEntry = NULL;
        HASH_FIND(hh, cnt, &nums[i], sizeof(int), qEntry);
        if (qEntry == NULL) {
            hashEntry * qEntry = (hashEntry*) malloc(sizeof(hashEntry));
            qEntry -> key = nums[i];
            qEntry -> val = 1;
            ans += nums[i];
            HASH_ADD(hh, cnt, key,sizeof(int), qEntry);
        }
        else if(qEntry->val == 1){
            ans -= nums[i];
            qEntry -> val = 2;
        }
    }
    hashEntry * curr = NULL, * next = NULL;
    HASH_ITER(hh, cnt, curr, next)
    {
        HASH_DEL(cnt, curr);
        free(curr);
    }
    return ans;
}

版权声明:如无特殊标注,文章均来自网络,本站编辑整理,转载时请以链接形式注明文章出处,请自行分辨。

本文链接:https://www.shbk5.com/dnsj/75327.html