Skip to content

Commit 846747a

Browse files
authored
Update README_EN.md
1 parent c2c799d commit 846747a

File tree

1 file changed

+36
-7
lines changed

1 file changed

+36
-7
lines changed

solution/0000-0099/0001.Two Sum/README_EN.md

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -353,19 +353,48 @@ class Solution {
353353
#### C
354354

355355
```c
356+
=#include <stdlib.h>
357+
356358
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
357-
for (int i = 0; i < numsSize; i++) {
358-
for (int j = i + 1; j < numsSize; j++) {
359-
if (nums[i] + nums[j] == target) {
360-
int* result = (int*)malloc(2 * sizeof(int));
361-
result[0] = i;
362-
result[1] = j;
359+
int capacity = 1;
360+
while (capacity < numsSize * 2) capacity <<= 1;
361+
int* keys = malloc(capacity * sizeof(int));
362+
int* vals = malloc(capacity * sizeof(int));
363+
char* used = calloc(capacity, sizeof(char));
364+
if (!keys || !vals || !used) {
365+
free(keys);
366+
free(vals);
367+
free(used);
368+
*returnSize = 0;
369+
return NULL;
370+
}
371+
for (int i = 0; i < numsSize; ++i) {
372+
int x = nums[i];
373+
int y = target - x;
374+
unsigned int h = (unsigned int) y & (capacity - 1);
375+
while (used[h]) {
376+
if (keys[h] == y) {
377+
int* res = malloc(2 * sizeof(int));
378+
res[0] = vals[h];
379+
res[1] = i;
363380
*returnSize = 2;
364-
return result;
381+
free(keys);
382+
free(vals);
383+
free(used);
384+
return res;
365385
}
386+
h = (h + 1) & (capacity - 1);
366387
}
388+
unsigned int h2 = (unsigned int) x & (capacity - 1);
389+
while (used[h2]) h2 = (h2 + 1) & (capacity - 1);
390+
used[h2] = 1;
391+
keys[h2] = x;
392+
vals[h2] = i;
367393
}
368394
*returnSize = 0;
395+
free(keys);
396+
free(vals);
397+
free(used);
369398
return NULL;
370399
}
371400
```

0 commit comments

Comments
 (0)