题目要求
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
- 只会存在一个有效答案
解题思路1:枚举法
进行两次for循环,然后使用if条件判断语句,将找出来的两个数动态分配内存到一个新的数组中,最后返回数组。时间复杂度为O(n的平方)
详细代码
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
for (int i = 0; i < numsSize; i++) {
for (int j = i + 1; j < numsSize; j++) {//在i之前的元素都和j计算过,因此直接从j+1算
if (nums[i] + nums[j] == target) {
int* ret = malloc(sizeof(int) * 2);//动态分配数组
ret[0] = i, ret[1] = j;//确定两数的位置
*returnSize = 2;
return ret;
}
}
}
*returnSize = 0;
return NULL;
}
解题思路2:哈希表
创建一个哈希表,对于每一个 x
,我们首先查询哈希表中是否存在 target - x
,然后将 x
插入到哈希表中,即可保证不会让 x
和自己匹配。时间复杂度O(n)
详细代码
struct hashTable {
int key;
int val;
UT_hash_handle hh;
};//定义了一个结构体包括键值对信息和用于哈希表操作的成员
struct hashTable* hashtable;//声明一个全局变量哈希表
struct hashTable* find(int ikey) {
struct hashTable* tmp;
HASH_FIND_INT(hashtable, &ikey, tmp);
return tmp;
}//find函数用于查找是否存在指定键值对,若存在就返回相应的结构体指针
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(hashtable, key, tmp);
} else {
it->val = ival;
}
}//insert函数用于插入新的键值对,如果已存在相同的键,更新它的值
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
hashtable = NULL;//将哈希表置为空
for (int i = 0; i < numsSize; i++) {
struct hashTable* it = find(target - nums[i]);
if (it != NULL) {
int* ret = malloc(sizeof(int) * 2);
ret[0] = it->val, ret[1] = i;
*returnSize = 2;
return ret;
}
insert(nums[i], i);
}
*returnSize = 0;
return NULL;
}