题目:
法一 解题思路:
由于 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;
}