From 1889a033c3b6754bdaafecf9ab6665deda1bee19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E6=98=82=E8=AC=99?= Date: Fri, 7 Oct 2022 11:18:22 +0800 Subject: [PATCH] =?UTF-8?q?add=20001.=E5=85=A9=E6=95=B8=E4=B9=8B=E5=92=8C?= =?UTF-8?q?=20C=E8=AA=9E=E8=A8=80(=E4=BD=BF=E7=94=A8=20leetcode=20?= =?UTF-8?q?=E6=94=AF=E6=8F=B4=E4=B9=8B=20ut=5Fhash=20=E5=87=BD=E5=BC=8F?= =?UTF-8?q?=E5=BA=AB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0001.两数之和.md | 81 +++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/problems/0001.两数之和.md b/problems/0001.两数之和.md index 5bedd0a0..bc618c15 100644 --- a/problems/0001.两数之和.md +++ b/problems/0001.两数之和.md @@ -352,5 +352,86 @@ List twoSum(List nums, int target) { } ``` +C: +```c + + +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ + +// leetcode 支持 ut_hash 函式庫 + + typedef struct { + int key; + int value; + UT_hash_handle hh; // make this structure hashable + } map; + +map* hashMap = NULL; + + void hashMapAdd(int key, int value){ + map* s; + // key already in the hash? + HASH_FIND_INT(hashMap, &key, s); + if(s == NULL){ + s = (map*)malloc(sizeof(map)); + s -> key = key; + HASH_ADD_INT(hashMap, key, s); + } + s -> value = value; + } + +map* hashMapFind(int key){ + map* s; + // *s: output pointer + HASH_FIND_INT(hashMap, &key, s); + return s; + } + + void hashMapCleanup(){ + map* cur, *tmp; + HASH_ITER(hh, hashMap, cur, tmp){ + HASH_DEL(hashMap, cur); + free(cur); + } + } + + void hashPrint(){ + map* s; + for(s = hashMap; s != NULL; s=(map*)(s -> hh.next)){ + printf("key %d, value %d\n", s -> key, s -> value); + } + } + + +int* twoSum(int* nums, int numsSize, int target, int* returnSize){ + int i, *ans; + // hash find result + map* hashMapRes; + hashMap = NULL; + ans = malloc(sizeof(int) * 2); + + for(i = 0; i < numsSize; i++){ + // key 代表 nums[i] 的值,value 代表所在 index; + hashMapAdd(nums[i], i); + } + + hashPrint(); + + for(i = 0; i < numsSize; i++){ + hashMapRes = hashMapFind(target - nums[i]); + if(hashMapRes && hashMapRes -> value != i){ + ans[0] = i; + ans[1] = hashMapRes -> value ; + *returnSize = 2; + return ans; + } + } + + hashMapCleanup(); + return NULL; +} +``` -----------------------