From 283349b569f25937f9981d5637ad25c777576f01 Mon Sep 17 00:00:00 2001 From: Kirito <1362050620@qq.com> Date: Tue, 19 Jun 2018 14:35:17 +0800 Subject: [PATCH] Create 1.c --- LeetCode-CN/1.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 LeetCode-CN/1.c diff --git a/LeetCode-CN/1.c b/LeetCode-CN/1.c new file mode 100644 index 0000000..e99dc98 --- /dev/null +++ b/LeetCode-CN/1.c @@ -0,0 +1,46 @@ +#include +#include +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; +}