https://leetcode.cn/problems/two-sum/submissions/588870256/?envType=study-plan-v2&envId=top-100-liked
参考快排算法 https://blog.csdn.net/oSKyTonight/article/details/129813861
/**
- Note: The returned array must be malloced, assume caller calls free().
*/
int Swap(int *a, int *b)
{
int c = *a;
*a = *b;
*b = c;
return 0;
}
int quickSort(int *a, int *b, int left, int right)
{
if (left >= right)
return 0;
int begin = left, end = right;
int keyi = left;//选定序列首元素为基准值while (left < right)
{//右边找小while (left < right && a[right] >= a[keyi])right--;//左边找大while (left < right && a[left] <= a[keyi])left++;//交换Swap(&a[left], &a[right]);Swap(&b[left], &b[right]);
}
//相遇时交换key和相遇位置的值
Swap(&a[keyi], &a[left]);
Swap(&b[keyi], &b[left]);keyi = left;//用keyi记录下本轮确定的基准值位置quickSort(a, b, begin, keyi - 1);//递归排序左区间[begin , keyi-1]
quickSort(a, b, keyi + 1, end);//递归排序右区间[keyi+1 , end]
return 0;
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
int *retList = (int *)malloc(2 * sizeof(int));
int *tempOrder = (int *)malloc(numsSize * sizeof(int));
*returnSize = 2;
memset(retList, 0, 2 * sizeof(int));
int a = 0;
int b = numsSize-1;
for (int i = 0; i < numsSize; i++)
{tempOrder[i] = i;
}
quickSort(nums, tempOrder, 0, numsSize-1);
while(a<b)
{if (nums[a]+nums[b]==target){retList[0] = tempOrder[a];retList[1] = tempOrder[b];break;}else if(nums[a] + nums[b] < target){a++;}else{b--;}
}
free(tempOrder);
return retList;
}