# [leetcode题解]001.Two Sum

You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

```struct element {
int num;
int loc;
};

int cmp(void *a, void *b) {
struct element *pa = (struct element *)a;
struct element *pb = (struct element *)b;

return pa->num - pb->num;
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int i = 0;
struct element *eles = malloc(sizeof(struct element) * numsSize);
int *res = malloc(2 * sizeof(int));
int idx = 0;
int li = 0, ri = numsSize - 1;

for (i = 0; i < numsSize; i++) {
eles[i].num = nums[i];
eles[i].loc = i;
}
qsort(eles, numsSize, sizeof(struct element), cmp);
while (li < ri) {
int sum = eles[li].num + eles[ri].num;
if (sum < target)
li++;
else if (sum > target)
ri--;
else {
res[0] = eles[li].loc;
res[1] = eles[ri].loc;
break;
}
}
return res;
}```