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
struct Pair {
int val;
int pos;
};
int cmp(const void *a, const void *b) {
const struct Pair *x = (const struct Pair*)a;
const struct Pair *y = (const struct Pair*)b;
return x->val - y->val;
}
int *twoSum(int numbers[], int n, int target) {
struct Pair *num = malloc(sizeof(struct Pair) * n);
for (int i = 0; i < n; ++i) {
num[i].val = numbers[i];
num[i].pos = i + 1;
}
qsort(num, n, sizeof(struct Pair), cmp);
int i = 0;
int j = n - 1;
while (i < j) {
int sum = num[i].val + num[j].val;
if (sum == target) {
break;
} else if (sum > target) {
--j;
} else { // sum < target:
++i;
}
}
int *res = malloc(sizeof(int) * 2);
if (num[i].pos < num[j].pos) {
res[0] = num[i].pos;
res[1] = num[j].pos;
} else {
res[0] = num[j].pos;
res[1] = num[i].pos;
}
return res;
}
本文介绍了一个算法,用于在给定数组中找到两个数,它们相加等于特定的目标数。此方法返回这两个数的索引,且确保索引1小于索引2。假设每个输入都有唯一解决方案。
153

被折叠的 条评论
为什么被折叠?



