16. 3Sum Closest

来源:互联网 发布:淘宝客服的上班时间 编辑:程序博客网 时间:2024/06/06 05:48

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

基本思路跟15差不多,就一些小细节改一改就ok了

class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        sort(nums.begin(), nums.end());        int len = nums.size();        int r, l, minn, ans;        minn = abs(nums[0] + nums[1] + nums[2] - target);        ans = nums[0] + nums[1] + nums[2];        for(int i = 0; i < len - 2; ++ i)        {            while(i > 0 && i < len - 2 && nums[i] == nums[i - 1])            i++;            l = i + 1;            r = len - 1;            while(l < r)            {                if(nums[i] + nums[l] + nums[r] == target)                return target;                if(abs(nums[i] + nums[l] + nums[r] - target) < minn)                {                    minn = abs(nums[i] + nums[l] + nums[r] - target);                    ans = nums[i] + nums[l] + nums[r];                }                if(nums[i] + nums[l] + nums[r] > target)                r--;                else                l++;            }        }        return ans;    }};
0 0