您的位置:首页 > 其它

16. 3Sum Closest

2016-03-26 10:57 295 查看
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).


Subscribe to see which companies asked this question

解释:

O(n^3)的复杂度,应该是可以优化的主要是担心会溢出。

可以优化的地方是用排序,下次再来。排序不能加,会超时。

代码:

class Solution {

public:

    int threeSumClosest(vector<int>& nums, int target) {

    //  sort(num.begin(),nums.end());

     float sum=nums[0]+nums[1]+nums[2];

     if(sum==target) return sum;

     float z=sum;

     float a1, a2;

     for(int i=0;i<nums.size();++i)

     for(int j=i+1;j<nums.size();++j)

     for(int t=j+1;t<nums.size();++t)

     {

         sum=nums[i]+nums[j]+nums[t];

         if(sum==target) return target;

         if(sum<target && z<target) {a1=target-sum;a2= target-z;if(a1<a2) z=sum;continue;}

         if(sum>target && z>target) {a1=sum-target;a2= z-target;if(a1<a2) z=sum;continue;}

         if(sum<target && z>target) {a1=target-sum;a2= z-target;if(a1<a2) z=sum;continue;}

         if(sum>target && z<target) {a1=sum-target;a2= target-z;if(a1<a2) z=sum;continue;}

     }

     return z;

    }

};

改进 2016-08-12

时间复杂度为n^2的解法是需要先排序。然后设置first,second, third三个位置,sum为三个位置的和,若等于target直接返回,若小于target则,second+1移动,若大于target则third-1移动。

代码:

class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
if(nums.size()<3) return 0;
int closet = nums[0]+nums[1]+nums[2];
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size()-2;++i)
{
if(i>0&&nums[i]==nums[i-1]) continue;
int j=i+1;
int t=nums.size()-1;
while(j<t)
{
int tempSum=nums[i]+nums[j]+nums[t];
if(tempSum==target) return target;
else if(tempSum<target) j++;
else t--;
if(abs(tempSum-target)<abs(closet-target))
{
closet=tempSum;
}
}
}
return closet;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  array