LeetCode 1.Two Sum

本文详细介绍了使用哈希表解决两数之和问题的算法实现过程,包括哈希表的初始化、元素插入、查找及返回结果等关键步骤。通过实例演示,清晰展示了算法的高效性和实用性。

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

#define MP 1000
struct Node
{
	int num;
	int pos;
	struct Node *next;
};
struct Node *hashTable[MP];

int* twoSum(int* nums, int numsSize, int target) {
    int i;
    memset(hashTable,0,sizeof(hashTable));

	for(i = 0;i<numsSize;i++)
	{
		int pos = 0;
		if(nums[i] < 0) pos = -nums[i]%MP;
		else pos = nums[i]%MP;
		
		struct Node *ptr = hashTable[pos];
        struct Node *hashNode = malloc(sizeof(struct Node));
        hashNode->num = nums[i];
        hashNode->next = ptr;
        hashNode->pos = i+1;
        hashTable[pos] = hashNode;
	}

	for(i = 0 ;i<numsSize;i++)
	{
		int pos = 0;
		int rest = target-nums[i];

		if(rest < 0) pos = -rest%MP;
		else pos = rest%MP;
		struct Node *ptr = hashTable[pos];
		while(ptr)
		{
			if(ptr->num == rest&&(i+1)!=ptr->pos)
			{
				int* result = (int*)malloc(sizeof(int*));
				result[0] = i+1;
				result[1] = ptr->pos;
				return result;
			}
			ptr = ptr->next;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值