Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
题目很简单,用哈希表就可以实现O(N)的算法了,但是有些细节要注意,第一,题目要求计算的结果保存在一个数组中并且返回,第二,最好不要定义全局变量,如果要用全局变量,使用前用一定memset初始化,如果上面两个没有注意,提交之后可能是WA
以下是我的AC的代码
#define MAX 10000
#define hash(key) (((key<0?key*(-1):key)^27)<<5)%MAX
struct HashNode{
int key;
int index;
struct HashNode*next;
};
struct HashNode map[MAX];
void put(int key,int index){
int i;
i=hash(key);
struct HashNode*node=(struct HashNode*)malloc(sizeof(struct HashNode));
node->key=key;
node->index=index;
node->next=map[i].next;
map[i].next=node;
}
int getIndex(int key,int index){
int i;
struct HashNode*node;
i=hash(key);
if((node=map[i].next)==NULL)
return -1;
while(node!=NULL){
if((node->key==key)&&(node->index!=index)){
return node->index;
}
node=node->next;
}
return -1;
}
int *twoSum(int numbers[], int n, int target) {
int i,sub,index;
int *result=(int*)malloc(sizeof(int)*2);
memset(map,0,sizeof(map));
for(i=0;i<n;i++){
put(numbers[i],i);
}
for(i=0;i<n;i++){
sub=target-numbers[i];
if((index=getIndex(sub,i))>0){
if(i+1<index+1){
result[0]=i+1;
result[1]=index+1;
}else{
result[0]=index+1;
result[1]=i+1;
}
printf("index1=%d, index2=%d",result[0],result[1]);
return result;
}
}
return result;
}