#1 Two Sum

题目连接:https://leetcode.com/problems/two-sum/


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)算法

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
struct HashNode {
    int key;
    int val;
};

struct HashMap {
    int size;
    struct HashNode **theLists;
};

int NextPrime(int n) {  //寻找下一素数作为表大小
    int i;
    if(n <= 3)
        return 3;
    while(1) {
        for(i = 2; i <= sqrt(n); ++i) {
            if(n % i == 0)
                return n;
        }
        ++n;
    }
}

struct HashMap* InitTable(int n)   //,建表,线性探测法解决冲突
{
    int size = NextPrime(n);
    struct HashMap *hashMap = (struct HashMap *)malloc(sizeof(struct HashMap));
    hashMap->size = size;
    hashMap->theLists = (struct HashNode **)calloc(size, sizeof(struct HashNode));
    return hashMap;
}

struct HashMap* Destroy(struct HashMap *hashMap) {  //销毁哈希表
    int i;
    for(i = 0; i < hashMap->size; ++i) {
        if(hashMap->theLists[i])
            free(hashMap->theLists[i]);
    }
    free(hashMap->theLists);
    free(hashMap);
}

void Insert(struct HashMap *hashMap, int key, int val) {    //将原数组的地址和数据存入哈希表
    int hash = abs(key) % hashMap->size;
    struct HashNode *node;
    while(node = hashMap->theLists[hash])
        hash = (hash + 1) % hashMap->size;
    node = (struct HashNode *)malloc(sizeof(struct HashNode));
    node->key = key;
    node->val = val;
    hashMap->theLists[hash] = node;
}
    
struct HashNode* Find(struct HashMap *hashMap, int key) {   //查表
    int hash = abs(key) % hashMap->size;
    struct HashNode *node;
    while(node = hashMap->theLists[hash]) {
        if(node->key == key)
            return node;
        hash = (hash + 1) % hashMap->size;
    }
    return NULL;
}
 
int* twoSum(int* nums, int numsSize, int target) {
    struct HashMap *hashMap;
    struct HashNode *node;
    int i;
    int *ret = (int *)malloc(2 * sizeof(int));
    hashMap = InitTable(2 * numsSize);      //表大小尽量大,减少冲突的开销
    for(i = 0; i < numsSize; ++i) {         //依次遍历数组
        if(node = Find(hashMap, target - nums[i])) {    //查看哈希表里是否存在target与当前数的差值,存在输出
            ret[0] = node->val + 1;
            ret[1] = i + 1;
            Destroy(hashMap);
            return ret;
        }
        else
            Insert(hashMap, nums[i], i);    //不存在,将当前值存入哈希表
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值