Skip to content

Instantly share code, notes, and snippets.

@LeeXun
Last active November 13, 2018 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeeXun/f1631c99a854d6bf0c90c9c08c6723d8 to your computer and use it in GitHub Desktop.
Save LeeXun/f1631c99a854d6bf0c90c9c08c6723d8 to your computer and use it in GitHub Desktop.
Leetcode
/**
* 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