Skip to content

Commit 78f06e2

Browse files
authored
Update README.md
1 parent 846747a commit 78f06e2

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

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

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,55 @@ class Solution {
353353
}
354354
```
355355

356+
#### C
357+
358+
```c
359+
#include <stdlib.h>
360+
361+
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
362+
int capacity = 1;
363+
while (capacity < numsSize * 2) capacity <<= 1;
364+
int* keys = malloc(capacity * sizeof(int));
365+
int* vals = malloc(capacity * sizeof(int));
366+
char* used = calloc(capacity, sizeof(char));
367+
if (!keys || !vals || !used) {
368+
free(keys);
369+
free(vals);
370+
free(used);
371+
*returnSize = 0;
372+
return NULL;
373+
}
374+
for (int i = 0; i < numsSize; ++i) {
375+
int x = nums[i];
376+
int y = target - x;
377+
unsigned int h = (unsigned int) y & (capacity - 1);
378+
while (used[h]) {
379+
if (keys[h] == y) {
380+
int* res = malloc(2 * sizeof(int));
381+
res[0] = vals[h];
382+
res[1] = i;
383+
*returnSize = 2;
384+
free(keys);
385+
free(vals);
386+
free(used);
387+
return res;
388+
}
389+
h = (h + 1) & (capacity - 1);
390+
}
391+
unsigned int h2 = (unsigned int) x & (capacity - 1);
392+
while (used[h2]) h2 = (h2 + 1) & (capacity - 1);
393+
used[h2] = 1;
394+
keys[h2] = x;
395+
vals[h2] = i;
396+
}
397+
*returnSize = 0;
398+
free(keys);
399+
free(vals);
400+
free(used);
401+
return NULL;
402+
}
403+
```
404+
356405
<!-- tabs:end -->
357406
358407
<!-- solution:end -->

0 commit comments

Comments
 (0)