1.题目
![](https://i-blog.csdnimg.cn/blog_migrate/9f309c26f1c59384e6d21a9c372cbdbc.png)
2.题意
已经排序的数组,查找两数之和为给定值,返回这两个数的次序
3.我的解法
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {
int *returnArray=calloc(2,sizeof(int));
int i=0,j=numbersSize-1;
while(i<j){
int twosum=numbers[i]+numbers[j];
if(twosum==target) break;
else if(twosum>target) j--;
else i++;
}
* returnSize=2;
returnArray[0]=i+1;
returnArray[1]=j+1;
return returnArray;
}
4.优秀解法
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {
int *result = (int *)malloc(sizeof(int) *2);
int i = 0;
while(i < numbersSize-1) {
if ( numbers[i] + numbers[numbersSize -1] == target) {
break;
} else if (numbers[i] + numbers[numbersSize -1] < target) {
i++;
} else {
numbersSize--;
}
}
result[0] = i+1;
result[1] = numbersSize ;
//printf(" %d %d", result[0], result[1]);
*returnSize = 2;
return result;
}
没有特殊之处,比较简单