File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
solution/0000-0099/0001.Two Sum Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -353,6 +353,55 @@ class Solution {
353
353
}
354
354
```
355
355
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
+
356
405
<!-- tabs:end -->
357
406
358
407
<!-- solution:end -->
You can’t perform that action at this time.
0 commit comments