本文主要是介绍Leetcode-16最接近的三数之和,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
我写的
int compare(const void * a, const void * b)
{return (*(int *)a - *(int *)b);
}
int threeSumClosest(int* nums, int numsSize, int target) {int res;int flag1 = 0,flag2 =0;int plusAns=0;int minusAns =0;qsort(nums,numsSize,sizeof(int),compare);plusAns = nums[numsSize-1]+nums[numsSize-2]+nums[numsSize-3];minusAns = nums[0]+nums[1]+nums[2];if(target >0 && plusAns <= 0){return plusAns;}if(target <0 &&minusAns>=0){return minusAns;}plusAns = plusAns -target;minusAns = minusAns -target;for(int i =0;i<numsSize-2;i++){if(i>0&&nums[i]==nums[i-1])continue;int start = i+1;int end = numsSize-1;while(start<end){res = nums[i] + nums[start] + nums[end]-target ;if(res == 0){return res+target;}else if(res>0){flag1 =1;end--;if(res<=plusAns)plusAns = res;}else if(res<0){flag2 =1;start++;if(res>=minusAns)minusAns = res;}}}int ans;if(flag1&&flag2){ans = plusAns<=abs(minusAns)?(plusAns+target):(minusAns+target);}else if(flag1){ans = plusAns+target;}else {ans = minusAns+target;}return ans;
}
别人写的范例
int abs(int tar){return tar>0?tar:-tar;
}
void quickSort(int* nums,int first,int end){int l=first,r=end;if(first>=end)return;int temp=nums[l];while(l<r){while(l<r && nums[r]>=temp)r--;if(l<r)nums[l]=nums[r];while(l<r && nums[l]<=temp)l++;if(l<r)nums[r]=nums[l];}nums[l]=temp;quickSort(nums,first,l-1);quickSort(nums,l+1,end);
}
int threeSumClosest(int* nums, int numsSize, int target) {int begin,end,i,sum,Min=INT_MAX;quickSort(nums,0,numsSize-1);for(i=0;i<numsSize-2;i++){if(i>0 && nums[i]==nums[i-1])continue;begin=i+1;end=numsSize-1;while(begin<end){sum=nums[i]+nums[begin]+nums[end];if(abs(sum-target)<abs(Min))Min=sum-target;if(sum==target)return target;else if(sum>target)end--;else begin++;}}return Min+target;
}
C++版本
class Solution {
public:int threeSumClosest(vector<int>& nums, int target) {sort(nums.begin(),nums.end());int colseSum = nums[0]+nums[1]+nums[2];for(int i=0;i<nums.size()-2;i++){// 去重,提高速度if(i && nums[i]==nums[i-1])continue;int l = i+1, r = nums.size()-1;while(l<r){int threeSum = nums[i]+nums[l]+nums[r];if(abs(threeSum-target)<abs(colseSum-target))colseSum = threeSum;if(threeSum==target)return target;if(threeSum>target){// 去重,提高速度if(l<r && nums[r]==nums[r-1])r--;r--;}else {// 去重,提高速度if(l<r && nums[l]==nums[l+1])l++;l++;}}}return colseSum;}
};
这篇关于Leetcode-16最接近的三数之和的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!