diff --git a/problems/0202.快乐数.md b/problems/0202.快乐数.md index f0a46a40..741a735a 100644 --- a/problems/0202.快乐数.md +++ b/problems/0202.快乐数.md @@ -315,5 +315,75 @@ class Solution { } ``` +C: +```C +typedef struct HashNodeTag { + int key; /* num */ + struct HashNodeTag *next; +}HashNode; + +/* Calcualte the hash key */ +static inline int hash(int key, int size) { + int index = key % size; + return (index > 0) ? (index) : (-index); +} + +/* Calculate the sum of the squares of its digits*/ +static inline int calcSquareSum(int num) { + unsigned int sum = 0; + while(num > 0) { + sum += (num % 10) * (num % 10); + num = num/10; + } + return sum; +} + +#define HASH_TABLE_SIZE (32) + +bool isHappy(int n){ + int sum = n; + int index = 0; + bool bHappy = false; + bool bExit = false; + /* allocate the memory for hash table with chaining method*/ + HashNode ** hashTable = (HashNode **)calloc(HASH_TABLE_SIZE, sizeof(HashNode)); + + while(bExit == false) { + /* check if n has been calculated */ + index = hash(n, HASH_TABLE_SIZE); + + HashNode ** p = hashTable + index; + + while((*p) && (bExit == false)) { + /* Check if this num was calculated, if yes, this will be endless loop */ + if((*p)->key == n) { + bHappy = false; + bExit = true; + } + /* move to next node of the same index */ + p = &((*p)->next); + } + + /* put n intot hash table */ + HashNode * newNode = (HashNode *)malloc(sizeof(HashNode)); + newNode->key = n; + newNode->next = NULL; + + *p = newNode; + + sum = calcSquareSum(n); + if(sum == 1) { + bHappy = true; + bExit = true; + } + else { + n = sum; + + } + } + + return bHappy; +} +``` -----------------------
diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 82be1829..45f19b6e 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -281,6 +281,38 @@ impl Solution { } } ``` + +C: +```C +int* intersection1(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){ + + int nums1Cnt[1000] = {0}; + int lessSize = nums1Size < nums2Size ? nums1Size : nums2Size; + int * result = (int *) calloc(lessSize, sizeof(int)); + int resultIndex = 0; + int* tempNums; + + int i; + + /* Calculate the number's counts for nums1 array */ + for(i = 0; i < nums1Size; i ++) { + nums1Cnt[nums1[i]]++; + } + + /* Check if the value in nums2 is existing in nums1 count array */ + for(i = 0; i < nums2Size; i ++) { + if(nums1Cnt[nums2[i]] > 0) { + result[resultIndex] = nums2[i]; + resultIndex ++; + /* Clear this count to avoid duplicated value */ + nums1Cnt[nums2[i]] = 0; + } + } + * returnSize = resultIndex; + return result; +} +``` + ## 相关题目 * 350.两个数组的交集 II