LeetCode题解:3sum closest

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

思路:

类似3Sum,只不过每次求和的时候都和已知的最接近的值比对一下,随时更新已经找到的最优解。

题解:

class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        int closest = numeric_limits<int>::max();
        int sum = 0;
        
        sort(begin(num), end(num));
        
        for(size_t i = 0; i < num.size() - 2; ++i)
        {
            int j = i + 1;
            int k = num.size() - 1;
            int expectation = target - num[i];
            
            while(j < k)
            {
                int diff = expectation - num[j] - num[k];
                if (abs(closest) > abs(diff))
                {
                    closest = diff;
                    sum = target - diff;
                }
                
                if (diff < 0)
                    k--;
                else if (diff > 0)
                    j++;
                else
                    return target;
            }
        }
        
        return sum;
    }
};


你可能感兴趣的:(LeetCode)