与leetcode15题目类似,大方向是使用双指针 三指针求解问题,细节稍有不同,AC代码如下:

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int n = nums.size();
        sort(nums.begin(),nums.end());
        int min_val = INT_MAX;
        int res = 0;

        for(int i = 0;i < n - 2;i++){
            int second = i + 1;
            int third = n -1;
            while(second < third)
            {
                int ans = nums[i]+nums[second]+nums[third];
                if(abs(target - ans) < min_val)
                {
                    min_val = abs(target - ans);
                    res = ans;
                }
                
                if(target > ans)
                    second++;
                else if (target < ans)
                    third--;
                else 
                    return ans;
            }
        }
        return res;
    }
};

运行效率:

Runtime: 4 ms, faster than 97.21% of C++ online submissions for 3Sum Closest.
Memory Usage: 9.7 MB, less than 90.42% of C++ online submissions for 3Sum Closest.