LeetCode 3 Sum 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).

The original problem is here.

The original code is here.

My Solution

I solve this problem in C++, as below:

*3Sum Closest
*Author: shuaijiang
*Email: zhaoshuaijiang8@gmail.com
using namespace std;

class Solution {
    int sumNum;
    int threeSumClosest(vector<int>& nums, int target) {
        int size = nums.size();
            return -1;
        sumNum = nums[0] + nums[1] + nums[2];
        for(int i=0;i<size-2;i++){
            if(i>0 && nums[i]==nums[i-1])
            twoSum(nums, i+1, size-1, nums[i], target);
            if(sumNum == target)
                return sumNum;
        return sumNum;
    void twoSum(vector<int> &nums, int start, int end, int num, int target){
            int oneSum = nums[start] + nums[end] + num;
            if(oneSum == target){
                sumNum = oneSum;
            if( oneSum < target ){
                if(abs(oneSum - target) < abs(sumNum - target))
                    sumNum = oneSum;
                start ++;
                if(abs(oneSum - target) < abs(sumNum - target))
                    sumNum = oneSum;
                end --;
        return ;


The problem is similar to 3sum, first sort the array. Then, for a number A in the array, select two numbers(B and C) from the set after A, which A+B+C is closest to the target. When select B and C, we find them from the head and tail of the array.