求:
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。node
你能夠假設每種輸入只會對應一個答案。可是,你不能重複利用這個數組中一樣的元素。數組
示例:spa
給定 nums = [2, 7, 11, 15], target = 9get
由於 nums[0] + nums[1] = 2 + 7 = 9
因此返回 [0, 1]hash
解:map
/**
* * Note: The returned array must be malloced, assume caller calls free().
* */
typedef
struct
HashNode {
int
key;
int
value;
struct
HashNode * Next;
}hashNode;
typedef
struct
Hash {
struct
HashNode * addr;
}hash;
hash* CreateHashMap(
int
size){
hash* hashMap = (hash*)malloc(
sizeof
(hash)*size);
int
i;
for
(i=
0
;i<size;i++){
hashMap[i].addr = NULL;
}
return
hashMap;
};
void
FreeHashMap(hash* hashMap,
int
size){
int
i;
for
(i=
0
;i<size;i++){
if
(hashMap[i].addr){
hashNode* node = hashMap[i].addr;
while
(node!=NULL){
hashNode* nextNode = node->Next;
free(node);
node = nextNode;
}
}
}
free(hashMap);
}
void
PrintHashmap(hash* hashMap,
int
size){
int
i;
for
(i=
0
;i<size;i++){
if
(hashMap[i].addr){
hashNode * node = hashMap[i].addr;
while
(node!=NULL){
printf(
"node[%s],key:%d,value:%d"
,i,node->key,node->value);
node = node->Next;
}
}
}
}
int
* twoSum(
int
* nums,
int
numsSize,
int
target,
int
* returnSize){
int
i;
hash* hashMap = CreateHashMap(numsSize);
for
(i=
0
;i<numsSize;i++){
int
value = nums[i];
int
expect = target - value;
int
mod1 = abs(value % numsSize);
int
mod2 = abs(expect % numsSize);
hashNode* newNode = (hashNode*)malloc(
sizeof
(hashNode));
newNode->key = i;
newNode->value = value;
if
(hashMap[mod1].addr){
newNode->Next = hashMap[mod1].addr;
hashMap[mod1].addr = newNode;
}
else
{
newNode->Next=NULL;
hashMap[mod1].addr = newNode;
}
if
(hashMap[mod2].addr){
hashNode * node = hashMap[mod2].addr;
while
(node!=NULL){
if
(node->key!=i && node->value + value == target){
*returnSize =
2
;
int
* returnArr = (
int
*)malloc(
sizeof
(
int
)*
2
);
returnArr[
0
] = node->key;
returnArr[
1
] = i;
return
returnArr;
}
else
{
node = node->Next;
}
}
}
}
return
0
;
};