LeetCode - Two Sum

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值