Problem Specs:
twosum.png
Solution(Implemented in C):
/**
* Abstract:Sort the array(with qsort) and for every element a[i], search(with bsearch)
* target - a[i].
* NOTE: An aux-array is allocated to preserve the original order so we can find the
* target pair's indices.
*/
int cmpfunc (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
int find(int a[], int n, int t, int si) {
for (int i = 0; i < n; i++) { if (i != si && a[i] == t) return i; }
return -1;
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
int *a = (int*)malloc(numsSize * sizeof(*a));
for (int i = 0; i < numsSize; i++) { *(a + i) = *(nums + i); }
qsort(a, numsSize, sizeof(*a), cmpfunc);
int *r = NULL;
for (int i = 0; i < numsSize; i++) {
int key = target - a[i];
int *item = (int*)bsearch(&key, a, numsSize, sizeof(*a), cmpfunc);
if (item != NULL && item != a + i) {
r = (int*)malloc(2 * sizeof(*r));
*r = i;
*(r + 1) = item - a;
break;
}
}
if (r != NULL) {
int *ret = (int*)malloc(2 * sizeof(ret));
*ret = find(nums, numsSize, a[*r], -1);
*(ret + 1) = find(nums, numsSize, a[*(r + 1)], *ret);
*returnSize = 2;
return ret;
}
if (returnSize != NULL) { *returnSize = 0; }
return NULL;
}









网友评论