LeetCode | 3Sum Closest(找到三个数使其和与target最接近)

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

题目解析:

找三个数,使其和与target最近。

一开始也是按照先选一个a,然后让target-a为要找的数据,进入子函数去循环。还想着什么时候要退出,是否要遍历完i+1…n个数据。

由于数的变化性比较大,我们找到i和j的差值与target-a相近了,但i和j之间的值可能更近,也可能更远。因此要遍历完全,并且没遍历一步都要与target-a比较。

我们干脆直接维持一个和sum = a+b+c。让sum-target变小时,就更新minSum。而左右指针也是同样的走向,当sum-target>0,end–;反之,begin++。

class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        if(num.size() < 3)
            return -1;
        sort(num.begin(),num.end());
        int min = num[0]+num[1]+num[2]-target;
        for(int i = 0;i < num.size()-1;i++){
            int begin = i+1;
            int end = num.size()-1;
            while(begin < end){
                int sum = num[i]+num[begin]+num[end]-target;
                if(sum==0) return target;
                if(abs(sum) < abs(min)) min = sum;
                if(sum<0)
                    begin++;
                else
                    end--;
            }
        }
        return min+target;
    }
};

点赞