6. 3Sum Closest

来源:互联网 发布:河南大学软件协会 编辑:程序博客网 时间:2024/06/04 00:02

题目

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).

思路

本题的解题思路可以参考上一篇博文:3Sum,具体解题思路和3Sum差不多,代码框架直接讨论,本质上比3Sum还简单,因为不需要去重,不多说了,上代码

代码

class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        if(nums.size()<3)            return 9999999999;        int min = nums[0]+nums[1]+nums[2],res;        sort(nums.begin(),nums.end());        for(int i=0;i<nums.size()-2;i++)        {            int l = i+1,r = nums.size()-1;            while(l<r)            {                res = nums[i]+nums[l]+nums[r];                   if(nums[i]+nums[l]+nums[r]==target)                {                    return target;                }                else if(nums[i]+nums[l]+nums[r]<target)                {                    min = abs(min-target)<abs(res-target)?min:res;                    l++;                }                else if(nums[i]+nums[l]+nums[r]>target)                {                    min = abs(min-target)<abs(res-target)?min:res;                    r--;                }            }        }        return min;      }};
原创粉丝点击