📜  C |运营商|问题11(1)

📅  最后修改于: 2023-12-03 15:13:47.585000             🧑  作者: Mango

C运营商问题11

问题描述

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。假设每个输入都只有一个解,且同样的元素不能重复使用。

示例:

输入: nums = [2, 7, 11, 15], target = 9 输出: [0, 1] 解释: nums[0] + nums[1] = 2 + 7 = 9

解题思路

本题可以使用哈希表来解决,遍历整个数组并把每个元素存储到哈希表中。对于每个元素a,判断target-a是否在哈希表中。如果存在,说明找到了这两个数,否则就把a加入哈希表中。时间复杂度为O(n),空间复杂度为O(n)。

代码实现
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct Node Node;
typedef struct HashTable HashTable;

struct Node {
    int key;
    int value;
    Node* next;
};

struct HashTable {
    Node** data;
    int size;
};

Node* createNode(int key, int value) {
    Node* node = (Node*)malloc(sizeof(Node));
    node->key = key;
    node->value = value;
    node->next = NULL;
    return node;
}

HashTable* createHashTable(int size) {
    HashTable* hashTable = (HashTable*)malloc(sizeof(HashTable));
    hashTable->data = (Node**)calloc(size, sizeof(Node*));
    hashTable->size = size;
    return hashTable;
}

void insert(HashTable* hashTable, int key, int value) {
    int index = abs(key) % hashTable->size;
    Node* node = hashTable->data[index];
    while (node != NULL) {
        if (node->key == key) {
            node->value = value;
            return;
        }
        node = node->next;
    }
    node = createNode(key, value);
    node->next = hashTable->data[index];
    hashTable->data[index] = node;
}

bool find(HashTable* hashTable, int key, int* value) {
    int index = abs(key) % hashTable->size;
    Node* node = hashTable->data[index];
    while (node != NULL) {
        if (node->key == key) {
            *value = node->value;
            return true;
        }
        node = node->next;
    }
    return false;
}

int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
    HashTable* hashTable = createHashTable(numsSize);
    for (int i = 0; i < numsSize; i++) {
        int complement = target - nums[i];
        int value;
        if (find(hashTable, complement, &value)) {
            int* result = (int*)malloc(2 * sizeof(int));
            result[0] = value;
            result[1] = i;
            *returnSize = 2;
            return result;
        }
        insert(hashTable, nums[i], i);
    }
    *returnSize = 0;
    return NULL;
}
测试用例
int main() {
    int nums[] = { 2, 7, 11, 15 };
    int target = 9;
    int returnSize;
    int* result = twoSum(nums, 4, target, &returnSize);
    for (int i = 0; i < returnSize; i++) {
        printf("%d ", result[i]);
    }
    printf("\n");
    free(result);
    return 0;
}

输出结果为:

0 1