-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path001_TwoSum.c
64 lines (54 loc) · 1.09 KB
/
001_TwoSum.c
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int i, j, key;
int* res = (int *)malloc(2 * sizeof(int));
int* tmp = (int *)malloc(numsSize * sizeof(int));
for(i = 0; i < numsSize; i++) {
*(tmp + i) = *(nums + i);
}
// Sorting tmp[] by using Insertion Sort.
for(j = 1; j < numsSize; j++) {
key = *(tmp +j);
i = j - 1;
while(i >=0 && *(tmp + i) > key) {
*(tmp + i + 1) = *(tmp + i);
i--;
}
*(tmp + i + 1) = key;
}
for(i = numsSize - 1; i > 0; i--) {
if(*(tmp + i) * 2 < target) {
break;
}
for(j = 0; j < i; j++) {
if(*(tmp + i) + *(tmp + j) > target) {
break;
}
if(*(tmp + i) + *(tmp + j) == target) {
int m = 0;
int n = 0;
for(m = 0; m < numsSize; m++) {
if((*(tmp + i) == *(nums + m)) || (*(tmp + j) == *(nums + m))) {
if(n == 0) {
*res = m;
n++;
}
else {
*(res + 1) = m;
}
}
}
free(tmp);
tmp = NULL;
return res;
}
}
}
*res = 0;
*(res + 1) = 0;
free(tmp);
tmp = NULL;
return res;
}