HashTable 示例 - 找出数组中和为指定值的两个数

数组 [2, 4, 6, 8],和为 8,则返回 [0, 2]
数组 [2, 3, 3],和为 6,则返回 [1, 2]

#include <stdio.h>
#include <stdlib.h>

typedef unsigned int Index;

typedef struct node {
    int data;
    struct node *next;
} ListNode, *Position, *List;

typedef struct HashTableStruct {
    List *data;
    int size;
} *HashTable;

HashTable init_ht(int size) {
    int i;
    HashTable ht;
    ht = malloc(sizeof(struct HashTableStruct));
    ht->size = size;
    ht->data = malloc(sizeof(List)*size);
    
    for (i = 0; i < size; i++) {
        ht->data[i] = malloc(sizeof(ListNode));
        ht->data[i]->next = NULL;
    }
    return ht;
}

Index hash_ht(HashTable ht, int v) {
    return abs(v) % ht->size;
}

void insert_ht(HashTable ht, int v) {
    Index i = hash_ht(ht, v);
    ListNode *tmp = malloc(sizeof(ListNode));
    tmp->data = v;
    tmp->next = ht->data[i]->next;
    ht->data[i]->next = tmp;
}

Position find_ht(HashTable ht, int v) {
    Index i = hash_ht(ht, v);
    Position tmp = ht->data[i];
    while(tmp->next != NULL) {
        if ((tmp->next)->data == v) {
            return tmp->next;
        }
    }
    return tmp->next;
}

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    HashTable ht;
    int i, j;
    int diff;
    int * ret;
    ht = init_ht(37);
    for (i = 0; i < numsSize; i++) {
        insert_ht(ht, nums[i]);
    }
    for (i = 0; i < numsSize; i++) {
        diff = target - nums[i];
        if (find_ht(ht, diff) != NULL) {
            for (j = 0; j < numsSize; j++) {
                if (nums[j] == diff) {
                    if (i == j) continue;
                    *returnSize = 2;
                    ret = malloc(sizeof(int) * 2);
                    ret[0] = i;
                    ret[1] = j;
                    return ret;
                }
            }
        }
    }
    *returnSize = 0;
    return NULL;
}


int main(void) {
    int nums[] = {3, 2, 4};
    int numsSize = 3;
    int target = 9;
    int *ret, returnSize;
    ret = twoSum(nums, numsSize, target, &returnSize);
    if (ret != NULL) {
        printf("%d, %d, %d\n", returnSize, ret[0], ret[1]);   
    }

    return 0;
}
发布了295 篇原创文章 · 获赞 158 · 访问量 101万+

猜你喜欢

转载自blog.csdn.net/kikajack/article/details/99698989