Given an array of integers that is already sorted in ascending order, 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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
//一开始很难理解Return an array of size *returnSize这句话的意思,尝试过多次后,发现给它赋值为返回数组长度才能通过,可以把它和numbersSize看做相同,
只是类型为指针,稍微复杂了一点而已
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {
int i,j;
int *res;
if(numbersSize<2)
return NULL;
*returnSize=2;
for(i=0;i<numbersSize-1;i++)
for(j=i+1;j<numbersSize;j++)
{
if(numbers[i]+numbers[j]==target)
{
res=(int *)calloc(2,sizeof(int *));
res[0]=i+1;res[1]=j+1;
}
}
return res;
}