001 - Two Sum

Two Sum

Total Accepted: 153895 Total Submissions: 808300 Difficulty: Medium

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

 
找出数列中的两个数,这两个数相加等于target,返回这两个数的数组下标
 
我的想法是:顺序读取数组,如果target减去当前值没有在hash表中,就把当前值放到hash表中,hash表中的元素为 数值 和 对应数组的下标加1
如果找到了就返回,理论上时间复杂读为O(n),因为只要遍历一遍就能找到结果了
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
#define PERM 2039
struct twoint {
	int index;
	int value;
	struct twoint *next;
};

void add2hash(struct twoint *hash[PERM], struct twoint *val)
{
	int in = val->value % PERM;
	if (in < 0) in += PERM;
	val->next = hash[in];
	hash[in] = val;
}

int findhash(struct twoint *hash[PERM], int val) 
{
	int in = val % PERM;
	if (in < 0) in += PERM;
	struct twoint *p = hash[in];
	while (p) {
		if (p->value == val) return p->index;
		p = p->next;
	}
	return -1;
}

/** memory leak */
int* twoSum(int* nums, int numsSize, int target) 
{
	struct twoint *hash[PERM] = {0};
	int *ret = NULL;
	int i, f;
	for(i = 0; i < numsSize; i++) {
		if ((f = findhash(hash, target - nums[i])) < 0) {
			struct twoint *t = (struct twoint *)calloc(sizeof(struct twoint), 1);
			t->index = i + 1;
			t->value = nums[i];
			add2hash(hash, t);
		} else {
			ret = (int *)calloc(sizeof(int), 2);
			ret[0] = f;
			ret[1] = i + 1;
			goto out;
		}
	}

out:
	return ret;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值