title: 剑指Offer 57.和为s的两个数字(c语言)
输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
示例1:
输入:nums = [2,7,11,15], target = 9
输出:[2,7] 或者 [7,2]
示例2:
输入:nums = [10,26,30,31,47,60], target = 40
输出:[10,30] 或者 [30,10]
限制:
$$
1 \leqslant nums.length \leqslant 10^5 \
1 \leqslant nums[i] \leqslant 10^6
$$
代码如下:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int* ret = (int*)malloc(2*sizeof(int));
if(NULL==nums || numsSize<2){
*returnSize = 0;
return NULL;
}
int low=0, high=numsSize-1;
while(low <= high)
{
if(nums[low]+nums[high] == target){
ret[0] = nums[low];
ret[1] = nums[high];
*returnSize = 2;
return ret;
} else if(nums[low]+nums[high] < target){
++low;
} else{
--high;
}
}
*returnSize = 0;
return ret;
}
标签:10,30,数字,nums,int,57,Offer,leqslant
From: https://www.cnblogs.com/blue-Suri/p/17342972.html