Leet Code - Two Sum
记录代码
/* Problem:
* Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution.And you may not use the same element twice.
*/
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define HASH_LEN 1000
typedef struct Data{
int value;
int index;
struct Data *next;
}Data;
typedef struct Hash{
Data *head;
Data *end;
}Hash;
void insertData(Hash *hash,Data *data);
int searchData(Hash *hash,int value,int i);
int *twoSum(int *nums,int numsSize,int target);
int main(void){
int numsSize,target;
scanf("%d",&numsSize);
int nums[numsSize];
printf("Please input the data:\n");
for(int i=0;i<numsSize;i++)
scanf("%d",&nums[i]);
printf("Please input the target:\n");
scanf("%d",&target);
int *ans;
ans=twoSum(nums,numsSize,target);
if(ans)
for(int i=0;i<2;i++)
printf("%d ",*(ans+i));
else
printf("No answers.");
return 0;
}
void insertData(Hash *hash,Data *data){
int key=(unsigned int)(data->value)%HASH_LEN;
if(!hash[key].head){
hash[key].head=data;
hash[key].end=data;
}
else{
hash[key].end->next=data;
hash[key].end=data;
}
}
int searchData(Hash *hash,int value,int i){
int key=(unsigned int)value%HASH_LEN;
Data *p=hash[key].head;
while(p){
if(p->value==value&&p->index!=i)
return p->index;
p=p->next;
}
return 0;
}
int *twoSum(int *nums,int numsSize,int target){
int *ans=(int *)malloc(2*sizeof(int));
Hash hash[HASH_LEN];
memset(hash,0,sizeof(Hash)*HASH_LEN);
Data data[HASH_LEN];
memset(data,0,sizeof(Data)*HASH_LEN);
for(int i=0;i<numsSize;i++){
data[i].value=nums[i];
data[i].index=i;
insertData(hash,&data[i]);
}
for(int i=0;i<numsSize;i++){
int x=i;
int y=searchData(hash,target-nums[i],i);
if(y){
ans[0]=x<y?x:y;
ans[1]=x+y-ans[0];
break;
}
else
return NULL;
}
return ans;
}