struct hashTable {
int key; /*数组元素值*/
int val; /*数组元素对应下标*/
UT_hash_handle hh;
};
/*Step1:创建哈希表*/
struct hashTable* Myhashtable;
struct hashTable * find( int ikey){
struct hashTable* tmp;
HASH_FIND_INT(Myhashtable, &ikey, tmp);
return tmp;
}
void insert( int ikey, int ival) {
struct hashTable* it = find(ikey);
if (it == NULL) {
struct hashTable* tmp = malloc(sizeof(struct hashTable));
tmp->key = ikey, tmp->val = ival;
HASH_ADD_INT(Myhashtable, key, tmp);
} else {
it->val = ival;
}
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
/*Step1:创建哈希表*/
//struct hashTable* Myhashtable;
Myhashtable = NULL;
/*Step2:遍历数组元素nums[i],查找target-nums[i]在不在哈希表中*/
for(int i = 0; i < numsSize; i++){
struct hashTable* it = find(target - nums[i]);
if(NULL == it){ /*如果在哈希表中没有找到target - nums[i], 则将nums[i]存入哈希表中*/
insert(nums[i], i);
}else{/*如果在哈希表中找到target - nums[i], 则返回下标*/
int* ret = malloc(sizeof(int) * 2);
ret[0] = it->val;
ret[1] = i ;
*returnSize = 2;
return ret;
}
}
/*Step3:如果遍历所有数组没有两者之和为target找到则返回NULL*/
*returnSize = 0;
return NULL;
}
另外一种指针传递
struct hashTable {
int key; /*数组元素值*/
int val; /*数组元素对应下标*/
UT_hash_handle hh;
};
/*Step1:创建哈希表*/
//struct hashTable* Myhashtable;
/********************************************
*功能:哈希表find函数
*参数1:指向哈希表指针的指针
*参数2:key
*参数3:value
********************************************/
struct hashTable * find(struct hashTable * *ihashtable, int ikey){
struct hashTable* tmp;
HASH_FIND_INT(*ihashtable, &ikey, tmp);
return tmp;
}
/********************************************
*功能:哈希表inser函数
*参数1:指向哈希表指针的指针
*参数2:key
*参数3:value
********************************************/
void insert(struct hashTable * *ihashtable, int ikey, int ival) {
struct hashTable* it = find(ihashtable, ikey);
if (it == NULL) {
struct hashTable* tmp = malloc(sizeof(struct hashTable));
tmp->key = ikey, tmp->val = ival;
HASH_ADD_INT(*ihashtable, key, tmp);
} else {
it->val = ival;
}
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
/*Step1:创建哈希表*/
struct hashTable* Myhashtable;
Myhashtable = NULL;
/*Step2:遍历数组元素nums[i],查找target-nums[i]在不在哈希表中*/
for(int i = 0; i < numsSize; i++){
struct hashTable* it = find(&Myhashtable, target - nums[i]);
if(NULL == it){ /*如果在哈希表中没有找到target - nums[i], 则将nums[i]存入哈希表中*/
insert(&Myhashtable, nums[i], i);
}else{/*如果在哈希表中找到target - nums[i], 则返回下标*/
int* ret = malloc(sizeof(int) * 2);
ret[0] = it->val;
ret[1] = i ;
*returnSize = 2;
return ret;
}
}
/*Step3:如果遍历所有数组没有两者之和为target找到则返回NULL*/
*returnSize = 0;
return NULL;
}
使用C语言通过哈希表高效解决LeetCode中两数之和的问题,达到O(1)的时间复杂度。介绍如何通过指针传递优化算法。
6276

被折叠的 条评论
为什么被折叠?



