1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
| int* two_sum(int* nums, int nums_size, int target, int* return_size);
int* two_sum(int* nums, int nums_size, int target, int* return_size) {
*return_size = 2;
int* solution = malloc(*return_size * sizeof(int));
if (solution == NULL) {
*return_size = 0;
return NULL;
}
for (int i = 0; i < nums_size; i++) {
for (int j = i + 1; j < nums_size; j++) {
if (nums[i] == target - nums[j]) {
solution[0] = i;
solution[1] = j;
return solution;
}
}
}
free(solution);
*return_size = 0;
return NULL;
}
int main(void) {
int nums[] = { 3, 8, 2, -12, 24 };
int nums_size = sizeof(nums) / sizeof(nums[0]);
int target = 12;
int return_size;
int* solution = two_sum(nums, nums_size, target, &return_size);
if (solution != NULL) {
printf("[%d %d]\n", solution[0], solution[1]);
free(solution);
} else {
printf("no matching combination\n");
}
return 0;
}
|