题目链接: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). 

这道题的要求是在给定的正整数数组中,找到三个数,使其之和最接近给定的数字target,并返回这三个数字之和。可以假设每组输入有确切解。

这道题的思路和之前的Two Sum3Sum差不多,简单方式是暴力查找,先排序,然后3层循环遍历数组,时间复杂度O(n3)。优化时,可以先固定一个数,再用两个指针l和r从这个数后面的两边往中间查找,逐个比较这三个数字之和与target的差距,记录最小的情况,当这三个数之和大于target的时候,r左移,而当之和小于target的时候,l右移,直到l和r相遇。这个其实就是在Two Sum外层加1层循环,也和3Sum的复杂度一样,因此时间复杂度是排序的O(nlogn)加O(n2),即O(n2)。

时间复杂度:O(n2)

空间复杂度:O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution
{
public:
    int threeSumClosest(vector<int> &num, int target)
    {
        sort(num.begin(), num.end());
        
        int closest = num[0] + num[1] + num[2];
        
        for(int i = 0; i < num.size() - 2; ++ i)
        {
            if(i > 0 && num[i] == num[i - 1]) // 跳过重复元素
                continue;
            
            int l = i + 1, r = num.size() - 1;
            while(l < r)
            {
                if(abs(num[i] + num[l] + num[r] - target) < abs(closest - target))
                    closest = num[i] + num[l] + num[r];
                
                if(num[l] + num[r] == target - num[i])
                    return target;
                else if(num[l] + num[r] > target - num[i])
                    -- r;
                else
                    ++ l;
            }
        }
        
        return closest;
    }
};