3Sum Closest

来源:互联网 发布:steam数据统计 编辑:程序博客网 时间:2024/03/29 03:45

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.

class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        int L = nums.size();        if(L == 3)        {            return nums[0]+nums[1]+nums[2];        }        sort(nums.begin(),nums.end());        int j,k,min = abs(target - (nums[0]+nums[1]+nums[L-1])),res = nums[0]+nums[1]+nums[2];        for(int i = 0;i < L-1; i++ )        {            //初始化下标            j = i+1;            k = L-1;            while(j < k)            {                int tmp = abs(target - (nums[i]+nums[j]+nums[k]));                if(tmp < min)                {                    min = tmp;                    res = nums[i]+nums[j]+nums[k];                }                if(nums[i]+nums[j]+nums[k] > target)                {                    --k;                    continue;                }                else if(nums[i]+nums[j]+nums[k] < target)                {                    ++j;                    continue;                }                else                    return target;            }        }        return res;    }};


0 0
原创粉丝点击