思路:
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {
int* ret=(int*)malloc(sizeof(int)*2);
*returnSize=2;
int left =0,right=numbersSize-1;
while(left < right)
{
if(numbers[left] + numbers[right] == target)
{
ret[0]=left+1;
ret[1]=right+1;
return ret;
}
else if(numbers[left] + numbers[right] > target)
{
right--;
}
else
{
left++;
}
}
return ret;
}
这题存在两个能够进行优化的地方:
int cmp(const void* a, const void* b)
{
return *(int*)a-*(int*)b;
}
int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {
qsort(nums,numsSize,sizeof(int),cmp);
int** ret=(int**)malloc(sizeof(int*)*numsSize*numsSize);
*returnColumnSizes=(int*)malloc(sizeof(int)*numsSize*numsSize);
int m=0;
for(int i=0;i<numsSize-2;i++)
{
//跳过重复数字
if(i > 0 && nums[i] == nums[i-1])
continue;
if(nums[i] + nums[i+1] + nums[i+2] > 0)
break;//优化一
if(nums[i] + nums[numsSize-1] + nums[numsSize-2] < 0)
continue;//优化二
int j=i+1;
int k=numsSize-1;
while(j < k)
{
if(nums[i] + nums[j] + nums[k] > 0)
k--;
else if(nums[i] + nums[j] + nums[k] < 0)
j++;
else
{
//添加三元组
int* arr=(int*)malloc(sizeof(int)*3);
arr[0]=nums[i];
arr[1]=nums[j];
arr[2]=nums[k];
ret[m]=arr;
(*returnColumnSizes)[m++]=3;
//跳过重复数字
for(j++;j < k && nums[j] == nums[j-1];j++);
for(k--;k > j && nums[k] == nums[k+1];k--);
}
}
}
*returnSize=m;
return ret;
}
最接近的三数之和-力扣
思路同第二题类似
int cmp(const void* a,const void* b)
{
return *(int*)a-*(int*)b;
}
int threeSumClosest(int* nums, int numsSize, int target) {
qsort(nums,numsSize,sizeof(int),cmp);
int sum=nums[0]+nums[1]+nums[2];
for(int i=0;i<numsSize-2;i++)
{
int j=i+1;
int k=numsSize-1;
while(j < k)
{
int tmp=nums[i]+nums[j]+nums[k];
if(abs(tmp-target) < abs(sum-target))
sum=tmp;
if(tmp > target)
k--;
else if(tmp < target)
j++;
else
return sum;
}
}
return sum;
}