Leetcode Q1: Two Sum

本文介绍了一个解决LeetCode经典题目“两数之和”的C语言实现方法。通过构建一个位图来快速查找目标值,从而有效地找到两个数的下标。此算法适用于包含正数和负数的数组,并确保了每个输入都恰好有一个解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个专栏是为了记录在leetcode刷题过程的记录,便于查看。

题目1:

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

int* twoSum(int* nums, int numsSize, int target) 
{
    int i = 0;
    int j = 0;
    int* res = (int*)malloc(sizeof(int) * 2);
    int* temp = (int*)malloc(sizeof(int) * 200000);     /* 相当于位图法,查找对应数时,无需进行比较,而是可以直接获得 */
    int* temp_pos = (int*)malloc(sizeof(int) * 200000); /* 记录位图中数对应原数组的位置 */

    int* bucket = &temp[100000];                        /* 考虑存在负数的情况 */
    int* bucket_pos = &temp_pos[100000];                


    for(i = 0; i < numsSize; i++)
    {
        bucket[nums[i]] = 1;                /* 题目中假设答案只有一个,那么存在重复数字的肯定不是答案,其实也无需进行统计 */
        bucket_pos[nums[i]] = i;            /* 记录位置 */
    }

    for(i = 0; i < numsSize; i++)
    {
        if (bucket[target - nums[i]])       
        {
            if (bucket_pos[target - nums[i]] == i)  /* 例:i=0, nums[i]=3, target=6*/
            {
                continue;
            }
            res[0] = i + 1;
            res[1] = bucket_pos[target - nums[i]] + 1;
            break;
        }
    }
    return res;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值