题目链接:https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof/
输入一个递增排序的数组和一个数字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 <= nums.length <= 10^5
1 <= nums[i] <= 10^6
双指针
1 /** 2 * Note: The returned array must be malloced, assume caller calls free(). 3 */ 4 int* twoSum(int* nums, int numsSize, int target, int* returnSize){ 5 int *new=(int *)malloc(sizeof(int)*2); 6 *returnSize=2; 7 int l=0,r=numsSize-1; 8 while(l<r){ 9 if(nums[l]+nums[r]==target){ 10 new[0]=nums[l]; 11 new[1]=nums[r]; 12 return new; 13 }else if(nums[l]+nums[r]<target){ 14 l++; 15 }else{ 16 r--; 17 } 18 } 19 return new; 20 }