給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和為目標值的那 兩個 整數,并返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,你不能重復利用這個數組中同樣的元素。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
題目來源:力扣(LeetCode),鏈接:https://leetcode-cn.com/problems/two-sum
解題思路:
- 暴力法:嵌套循環,固定一個數,然后在后面度部分進行查找,時間復雜度是O(n^2),
- 一遍哈希法:建立一個哈希表,哈希表中,值為key,位置為value。遍歷的時候,先去查找target - nums[i] 是否在哈希表中,如果在的話直接返回結果,如果不在的話。將當前值加入哈希表中。
C語言代碼如下,使用https://troydhanson.github.io/uthash/提供的哈希表,不再額外造輪子
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
struct hashtable {
int key; /* key */
int value;
UT_hash_handle hh; /* makes this structure hashable */
};
void add(struct hashtable **table, int num, int idx) {
//申請一個結構存放數據
struct hashtable *s;
s = malloc(sizeof(struct hashtable));
s->key = num;
s->value = idx;
HASH_ADD_INT((*table), key, s ); /* id: name of key field */
}
//一遍哈希法
// 從頭往后遍歷,檢查target - nums[i] 是否在hash表中
// 如果不在, 以值為key,下標為value進行存放
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
struct hashtable *table = NULL; //新建哈希表
struct hashtable *tmp; //用于存放找到中間結果
*returnSize = 2;
int *res = (int*)malloc(sizeof(int) * *returnSize);
int remain;
for(int i = 0; i < numsSize; i++){
remain = target - nums[i]; //剩余值
// 在表table中查找remin, 如果有結果,返回tmp
HASH_FIND_INT(table, &remain, tmp);
if ( tmp == NULL ){
add(&table, nums[i], i);
} else {
res[1] = i;
res[0] = tmp->value;
break;
}
}
return res;
}