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;
}