leetcode--twoSum

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值