Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
解题思路:
(1)复制给定的数组,并进行希尔排序
(2)在复制的数组中找到和为target的那两个元素
(3)在原数组中找到上述两个元素的位置
int* twoSum(int* nums, int numsSize, int target) {
int* numsTemp = (int*)malloc(sizeof(int)*numsSize);
for (int i = 0; i < numsSize; i++)
numsTemp[i] = nums[i];
//希尔排序
for (int Incre = numsSize/2; Incre > 0; Incre /= 2)
{
for (int i = Incre; i < numsSize; i++)
{
int temp = numsTemp[i];
int j;
for (j = i; j >= Incre; j -= Incre)
{
if (temp < numsTemp[j-Incre])
numsTemp[j] = numsTemp[j-Incre];
else
break;
}
numsTemp[j] = temp;
}
}
int start = 0;
int end = numsSize-1;
while (start < end)
{
int sum = numsTemp[start] + numsTemp[end];
if (sum == target)
{
break;
}
else if (sum > target)
{
end--;
}
else
start++;
}
int* res = (int*)malloc(sizeof(int)*2);
bool flags = false;
for (int i = 0; i < numsSize; i++)
{
if (!flags)
{
if (nums[i] == numsTemp[start] || nums[i] == numsTemp[end])
{
res[0] = i+1;
flags = true;
}
}
else
{
if (nums[i] == numsTemp[start] || nums[i] == numsTemp[end])
{
res[1] = i+1;
break;
}
}
}
free(numsTemp);
return res;
}