Skip to content

Commit e6642a9

Browse files
authored
Update Solution.c
1 parent 78f06e2 commit e6642a9

File tree

1 file changed

+36
-7
lines changed

1 file changed

+36
-7
lines changed
Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,44 @@
1+
#include <stdlib.h>
2+
13
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
2-
for (int i = 0; i < numsSize; i++) {
3-
for (int j = i + 1; j < numsSize; j++) {
4-
if (nums[i] + nums[j] == target) {
5-
int* result = (int*) malloc(2 * sizeof(int));
6-
result[0] = i;
7-
result[1] = j;
4+
int capacity = 1;
5+
while (capacity < numsSize * 2) capacity <<= 1;
6+
int* keys = malloc(capacity * sizeof(int));
7+
int* vals = malloc(capacity * sizeof(int));
8+
char* used = calloc(capacity, sizeof(char));
9+
if (!keys || !vals || !used) {
10+
free(keys);
11+
free(vals);
12+
free(used);
13+
*returnSize = 0;
14+
return NULL;
15+
}
16+
for (int i = 0; i < numsSize; ++i) {
17+
int x = nums[i];
18+
int y = target - x;
19+
unsigned int h = (unsigned int) y & (capacity - 1);
20+
while (used[h]) {
21+
if (keys[h] == y) {
22+
int* res = malloc(2 * sizeof(int));
23+
res[0] = vals[h];
24+
res[1] = i;
825
*returnSize = 2;
9-
return result;
26+
free(keys);
27+
free(vals);
28+
free(used);
29+
return res;
1030
}
31+
h = (h + 1) & (capacity - 1);
1132
}
33+
unsigned int h2 = (unsigned int) x & (capacity - 1);
34+
while (used[h2]) h2 = (h2 + 1) & (capacity - 1);
35+
used[h2] = 1;
36+
keys[h2] = x;
37+
vals[h2] = i;
1238
}
1339
*returnSize = 0;
40+
free(keys);
41+
free(vals);
42+
free(used);
1443
return NULL;
1544
}

0 commit comments

Comments
 (0)