现在的位置: 首页 > 综合 > 正文

3sum closest

2019年07月26日 ⁄ 综合 ⁄ 共 707字 ⁄ 字号 评论关闭

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类似,需要给数组排序,然后再计算。时间复杂度为O(N^2)。

class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        sort(num.begin(), num.end());
        int i, len = num.size(),L,R;
        int Min = INT_MAX;
        int res;
        for(i=0; i<len; ++i)
        {
            for(L=i+1,R=len-1; L<R;)
            {
                if(abs(num[i]+num[L]+num[R]-target) < Min)
                {
                    Min = abs(num[i]+num[L]+num[R]-target);
                    res = num[i]+num[L]+num[R];
                }    
                if (num[i]+num[L]+num[R] < target)
                {
                    ++L;
                }    
                else if (num[i]+num[L]+num[R] > target)
                {
                    --R;
                }    
                else 
                {
                    return res;
                }    
            }    
        }    
        return res;
    }
};
【上篇】
【下篇】

抱歉!评论已关闭.