You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
89 lines
2.2 KiB
89 lines
2.2 KiB
2 years ago
|
/**
|
||
2 years ago
|
* File: two_sum.c
|
||
2 years ago
|
* Created Time: 2023-01-19
|
||
|
* Author: Reanon (793584285@qq.com)
|
||
|
*/
|
||
|
|
||
2 years ago
|
#include "../utils/common.h"
|
||
2 years ago
|
|
||
2 years ago
|
/* 方法一:暴力枚举 */
|
||
2 years ago
|
int *twoSumBruteForce(int *nums, int numsSize, int target, int *returnSize) {
|
||
|
for (int i = 0; i < numsSize; ++i) {
|
||
|
for (int j = i + 1; j < numsSize; ++j) {
|
||
|
if (nums[i] + nums[j] == target) {
|
||
2 years ago
|
int *res = malloc(sizeof(int) * 2);
|
||
|
res[0] = i, res[1] = j;
|
||
2 years ago
|
*returnSize = 2;
|
||
2 years ago
|
return res;
|
||
2 years ago
|
}
|
||
|
}
|
||
|
}
|
||
|
*returnSize = 0;
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
/* 哈希表 */
|
||
|
struct hashTable {
|
||
|
int key;
|
||
|
int val;
|
||
2 years ago
|
UT_hash_handle hh; // 基于 uthash.h 实现
|
||
2 years ago
|
};
|
||
|
|
||
|
typedef struct hashTable hashTable;
|
||
|
|
||
2 years ago
|
/* 哈希表查询 */
|
||
2 years ago
|
hashTable *find(hashTable *h, int key) {
|
||
|
hashTable *tmp;
|
||
|
HASH_FIND_INT(h, &key, tmp);
|
||
|
return tmp;
|
||
|
}
|
||
|
|
||
2 years ago
|
/* 哈希表元素插入 */
|
||
2 years ago
|
void insert(hashTable *h, int key, int val) {
|
||
|
hashTable *t = find(h, key);
|
||
|
if (t == NULL) {
|
||
|
hashTable *tmp = malloc(sizeof(hashTable));
|
||
|
tmp->key = key, tmp->val = val;
|
||
|
HASH_ADD_INT(h, key, tmp);
|
||
|
} else {
|
||
|
t->val = val;
|
||
|
}
|
||
|
}
|
||
|
|
||
2 years ago
|
/* 方法二:辅助哈希表 */
|
||
2 years ago
|
int *twoSumHashTable(int *nums, int numsSize, int target, int *returnSize) {
|
||
|
hashTable *hashtable = NULL;
|
||
|
for (int i = 0; i < numsSize; i++) {
|
||
|
hashTable *t = find(hashtable, target - nums[i]);
|
||
|
if (t != NULL) {
|
||
2 years ago
|
int *res = malloc(sizeof(int) * 2);
|
||
|
res[0] = t->val, res[1] = i;
|
||
2 years ago
|
*returnSize = 2;
|
||
2 years ago
|
return res;
|
||
2 years ago
|
}
|
||
|
insert(hashtable, nums[i], i);
|
||
|
}
|
||
|
*returnSize = 0;
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
2 years ago
|
/* Driver Code */
|
||
2 years ago
|
int main() {
|
||
|
// ======= Test Case =======
|
||
|
int nums[] = {2, 7, 11, 15};
|
||
2 years ago
|
int target = 13;
|
||
2 years ago
|
// ====== Driver Code ======
|
||
|
int returnSize;
|
||
|
int *res = twoSumBruteForce(nums, sizeof(nums) / sizeof(int), target, &returnSize);
|
||
|
// 方法一
|
||
|
printf("方法一 res = ");
|
||
|
printArray(res, returnSize);
|
||
|
|
||
|
// 方法二
|
||
|
res = twoSumHashTable(nums, sizeof(nums) / sizeof(int), target, &returnSize);
|
||
|
printf("方法二 res = ");
|
||
|
printArray(res, returnSize);
|
||
2 years ago
|
|
||
2 years ago
|
return 0;
|
||
2 years ago
|
}
|