首页 > 代码库 > [leetcode]3 Sum closest

[leetcode]3 Sum closest

问题描述:

Given an array S of n integers, find three integers inS 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).

基本思路:

本题可以利用上一篇《3 Sum》相同的思路来处理。就是对数组排序,然后利用数字之间的序关系减少对不必要情况的处理。


代码:

int threeSumClosest(vector<int> &num, int target)   //C++
    {
        //You may assume that each input would have exactly one solution.
        int sum = num[0]+num[1]+num[2];
        int dif = abs(sum -target);
        
        sort(num.begin(), num.end());
        for (int i = 0; i < num.size() - 2;)
        {
            int l = i + 1, r = num.size() - 1;
            while (l < r)
            {
                int tmpdif = num[l] + num[r] + num[i] - target;
                if ( tmpdif <= -dif) l++;
                else if (tmpdif > -dif && tmpdif < dif)
                {
                    dif = abs(tmpdif);
                    sum = num[l] + num[r] + num[i];
                    if(tmpdif < 0)
                        do { l++; }while (l < r && num[l - 1] == num[l]);
                    else if(tmpdif > 0)
                        do { r--; }while (l < r && num[r + 1] == num[r]);
                    else return target;
                }
                else r--;
            }
            do{ i++; }while (i < num.size() - 1 && num[i - 1] == num[i]);
        }
        return sum;
        }
  


[leetcode]3 Sum closest