C 数据结构与算法 — 数组取数求目标和

目录

文章目录

题目

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的两个整数,并返回它们的数组下标。

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

int *two_sum(int *nums, int nums_size, int target) {
    
    
    // 哈希表,用于存储整数和下标
    int hash[10000] = {
    
    0};
    // 结果数组,存放两个整数的下标
    static int result[2];

    for(int i = 0; i < nums_size; i++) {
    
    
        // 取目标值和当前整数的差值
        int complement = target - nums[i];

        // 如果差值不在 hash 中,则添加,key 为 整数,value 为 idx+1(避免出现为 0 的情况)。
        if (0 == hash[complement]) {
    
    
            hash[nums[i]] = i + 1;
        } else {
    
    
            // 如果差值存在 hash 中,则直接取出整数的 idx-1(因为存的时候 +1 了)。
            result[0] = hash[complement] - 1;
            // 另外一个 idx 就是当前整数。
            result[1] = i;
            return result;
        }
    }
    return NULL;
}

int main() {
    
    
    int nums[] = {
    
    1, 2, 3, 4, 5};  // 随机数组
    int nums_size = 5;             // 数组长度
    int target = 6;                // 目标和

    int *result = two_sum(nums, nums_size, target);
    if (NULL == result) {
    
    
        printf("No result found!\n");
    } else {
    
    
        printf("result index: [%d, %d]\n", result[0], result[1]);
    }
}
  • 时间复杂度为:O(n),只遍历了包含有 n 个元素的数组一次,在 hash 表中进行的每次查找只花费 O(1) 的时间。
  • 空间复杂度为:O(n), 所需的内存空间取决于哈希表中存储的元素数量,该表最多需要存储 n 个元素。

猜你喜欢

转载自blog.csdn.net/Jmilk/article/details/130139820