LeetCode:16. 3Sum Closest

题目:
LeetCode: 16. 3Sum Closest

描述:

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. 3Sum基本上一致的。

 思路:
 1、由于是找出和为target的元素,首先对vector进行排序,有利于进一步处理。
 2、三个数字和首先想到的是固定一个数值,另两个数字作为游标遍历vector。例如:[-1, 0, 1, 2, -1, -4]中,排序后为[ -4, -1, -1, 0, 1, 2] 固定最小的首个数字为k1=-4,令k2从 -1 向右移动,k3 = 2向左移动。直至 k3游标移到k2游标位置,
 3、根据k2 + k3 + k1 ? target 的关系,来决定游标移动方向,k1固定,当k2 + k3 + k1 > 0时,k3 左移(减小三个数和),反之k2右移。当相等时,存入数组,并令k2 k3同时移动,便面出现多组重复集合的情况。
 

代码:

int threeSumClosest(vector<int>& vecNum, int nTarget) {
    if (vecNum.size() < 3)
    {
        return INT_MAX;
    }
    sort(vecNum.begin(), vecNum.end());

    int nDiff = INT_MAX;

    for (vector<int>::iterator iterBg = vecNum.begin(); iterBg < vecNum.end() - 2; iterBg++)
    {
        if (iterBg > vecNum.begin() && *(iterBg - 1) == *iterBg)
        {
            continue;
        }

        vector<int>::iterator iterL = iterBg + 1;
        vector<int>::iterator iterR = vecNum.end() - 1;

        while (iterL < iterR)
        {
            int nSum = *iterBg + *iterL + *iterR;
            if (nTarget > nSum)
            {
                iterL++;
                while (*iterL == *(iterL - 1) && iterL < iterR)
                {
                    iterL++;
                }
            }
            else if (nTarget < nSum)
            {
                iterR--;
                while (*iterR == *(iterR + 1) && iterL < iterR)
                {
                    iterR--;
                }
            }
            else
            {
                return nTarget;
            }

            int nTemp = abs(nTarget - nSum);
            if (abs(nDiff) > nTemp)
            {
                nDiff = nTarget - nSum;
            }
        }
    }
    return nTarget - nDiff;
}

备注:
可以参考15. 3Sum.

posted @ 2017-06-29 19:10  suilin  阅读(125)  评论(0编辑  收藏  举报