File tree Expand file tree Collapse file tree 1 file changed +36
-7
lines changed
solution/0000-0099/0001.Two Sum Expand file tree Collapse file tree 1 file changed +36
-7
lines changed Original file line number Diff line number Diff line change @@ -353,19 +353,48 @@ class Solution {
353
353
#### C
354
354
355
355
``` c
356
+ =#include <stdlib.h>
357
+
356
358
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;
363
380
* returnSize = 2;
364
- return result;
381
+ free(keys);
382
+ free(vals);
383
+ free(used);
384
+ return res;
365
385
}
386
+ h = (h + 1) & (capacity - 1);
366
387
}
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;
367
393
}
368
394
* returnSize = 0;
395
+ free(keys);
396
+ free(vals);
397
+ free(used);
369
398
return NULL;
370
399
}
371
400
```
You can’t perform that action at this time.
0 commit comments