Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1744c21

Browse files
Merge pull request youngyangyang04#1684 from askaldk/master
add 001.兩數之和 C語言(使用 leetcode 支援之 ut_hash 函式庫)
2 parents b7329a1 + 1889a03 commit 1744c21

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

‎problems/0001.两数之和.md

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,5 +352,86 @@ List<int> twoSum(List<int> nums, int target) {
352352
}
353353
```
354354

355+
C:
356+
```c
357+
358+
359+
/**
360+
* Note: The returned array must be malloced, assume caller calls free().
361+
*/
362+
363+
// leetcode 支持 ut_hash 函式庫
364+
365+
typedef struct {
366+
int key;
367+
int value;
368+
UT_hash_handle hh; // make this structure hashable
369+
} map;
370+
371+
map* hashMap = NULL;
372+
373+
void hashMapAdd(int key, int value){
374+
map* s;
375+
// key already in the hash?
376+
HASH_FIND_INT(hashMap, &key, s);
377+
if(s == NULL){
378+
s = (map*)malloc(sizeof(map));
379+
s -> key = key;
380+
HASH_ADD_INT(hashMap, key, s);
381+
}
382+
s -> value = value;
383+
}
384+
385+
map* hashMapFind(int key){
386+
map* s;
387+
// *s: output pointer
388+
HASH_FIND_INT(hashMap, &key, s);
389+
return s;
390+
}
391+
392+
void hashMapCleanup(){
393+
map* cur, *tmp;
394+
HASH_ITER(hh, hashMap, cur, tmp){
395+
HASH_DEL(hashMap, cur);
396+
free(cur);
397+
}
398+
}
399+
400+
void hashPrint(){
401+
map* s;
402+
for(s = hashMap; s != NULL; s=(map*)(s -> hh.next)){
403+
printf("key %d, value %d\n", s -> key, s -> value);
404+
}
405+
}
406+
407+
408+
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
409+
int i, *ans;
410+
// hash find result
411+
map* hashMapRes;
412+
hashMap = NULL;
413+
ans = malloc(sizeof(int) * 2);
414+
415+
for(i = 0; i < numsSize; i++){
416+
// key 代表 nums[i] 的值,value 代表所在 index;
417+
hashMapAdd(nums[i], i);
418+
}
419+
420+
hashPrint();
421+
422+
for(i = 0; i < numsSize; i++){
423+
hashMapRes = hashMapFind(target - nums[i]);
424+
if(hashMapRes && hashMapRes -> value != i){
425+
ans[0] = i;
426+
ans[1] = hashMapRes -> value ;
427+
*returnSize = 2;
428+
return ans;
429+
}
430+
}
431+
432+
hashMapCleanup();
433+
return NULL;
434+
}
435+
```
355436
-----------------------
356437
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /