/**
* Note: The returned array must be malloced, assume caller calls free().
*/structcmhash_st{int key;int value;
UT_hash_handle hh;};int*twoSum(int* nums,int numsSize,int target,int* returnSize){structcmhash_st*hmap =NULL;structcmhash_st*entry =NULL;int i;int num;int*ret =NULL;//建立hash表for(i =0; i < numsSize; i++){
entry =calloc(1,sizeof(structcmhash_st));
entry->key = nums[i];
entry->value = i;HASH_ADD_INT(hmap, key, entry);
entry =NULL;}//查询值for(i =0; i < numsSize; i++){
num = target - nums[i];HASH_FIND_INT(hmap,&num, entry);if(entry !=NULL&& entry->value != i){
ret =calloc(2,sizeof(int));
ret[0]= i;
ret[1]= entry->value;*returnSize =2;return ret;}}return ret;}
注意点
需要判断不能重复取,即需要判断entry-value != i的场景;
注意设置返回长度*returnSize = 2
内存使用需要优化(待续)
结果
Python3
classSolution:deftwoSum(self, nums: List[int], target:int)-> List[int]:
hmap ={}for i,val inenumerate(nums,0):
hmap[val]= i
for i, val inenumerate(nums,0):if target - val in hmap:if hmap[target - val]!= i:return[i, hmap[target - val]]return[]
LeetCode刷题笔记-1.两数之和C代码注意点结果![在这里插入图片描述](https://img-blog.csdnimg.cn/fb728bc4f54d4215925bbde60ffb5267.png)题目C代码/** * Note: The returned array must be malloced, assume caller calls free(). */struct cmhash_st { int key; int value; UT_hash_han