Last active
November 13, 2018 15:33
-
-
Save LeeXun/f1631c99a854d6bf0c90c9c08c6723d8 to your computer and use it in GitHub Desktop.
Leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Note: The returned array must be malloced, assume caller calls free(). | |
*/ | |
int* twoSum(int* nums, int numsSize, int target) { | |
int i, j; | |
int *ans = malloc(sizeof(int)*2); | |
for(i=0; i<numsSize; i++) { | |
for(j=0; j<numsSize; j++) { | |
if(nums[i]+nums[j] == target && i != j) { | |
ans[0] = j; | |
ans[1] = i; | |
break; | |
} | |
} | |
} | |
return ans; | |
} | |
/** | |
* Note: The returned array must be malloced, assume caller calls free(). | |
*/ | |
#define DELTA 1 | |
int* twoSum(int* nums, int numsSize, int target) { | |
int max, min, i; | |
max = min = nums[0]; | |
for(i=0;i<numsSize;i++) { | |
if(nums[i] < min) min = nums[i]; | |
if(nums[i] > max) max = nums[i]; | |
} | |
int *a = (int*)calloc((max-min+1), sizeof(int)); | |
int *b = (int*)malloc(sizeof(int)*2); | |
b[0] = b[1] = -1; | |
for(i=0;i<numsSize;i++) { | |
int lookfor = target-nums[i]; | |
if(lookfor < min || lookfor > max) continue; | |
int that = lookfor - min; | |
int this = nums[i] - min; | |
if(a[that]) { | |
printf("%d", a[that]); | |
b[0] = a[that]-DELTA; | |
b[1] = i; | |
break; | |
} else { | |
a[this] = i+DELTA; | |
} | |
} | |
return b; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment