Create 1.c

This commit is contained in:
Kirigaya Kazuto 2018-06-19 14:35:17 +08:00 committed by GitHub
parent 8e77a6ead0
commit 283349b569
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

46
LeetCode-CN/1.c Normal file
View File

@ -0,0 +1,46 @@
#include <stdlib.h>
#include <string.h>
typedef struct pack
{
int val;
int pos;
}pack;
int qcmp(const void* a, const void* b)
{
return ((pack*)a)->val - ((pack*)b)->val;
}
int* twoSum(int* nums, int numsSize, int target) {
pack* p = (pack*)malloc(sizeof(pack)*numsSize);
for (int i = 0; i < numsSize; i++)
{
p[i].val = nums[i];
p[i].pos = i;
}
qsort(p, numsSize, sizeof(pack), qcmp);
int L = 0;
int R = numsSize - 1;
while (L < R)
{
int sum = p[L].val + p[R].val;
if (sum == target)
{
int* m = (int*)malloc(sizeof(int) * 2);
m[0] = p[L].pos;
m[1] = p[R].pos;
return m;
}
else if (sum < target)
{
L++;
}
else if (sum > target)
{
R--;
}
}
return NULL;
}