[Leetcode C++] 3Sum Closest

Problem

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

Solution

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int minDiff = INT_MAX;
        if(nums.size()<3) return minDiff;
        sort(nums.begin(), nums.end());
        for(int i=0; i<nums.size()-2; i++){
            int left = i+1;
            int right = nums.size()-1;
            while(left < right){ 
                int currDiff = nums[i] + nums[left] + nums[right] - target; 
                
                //update diff 
                if(abs(minDiff) > abs(currDiff)) 
                   minDiff = currDiff;
                
                //special case
                if(currDiff == 0) break;
                else if (currDiff < 0) left++;
                else right--;
            }
        }
        return target + minDiff;
    }
};

Analysis

This problem is similar to 3Sum problemĀ http://mytechroad.com/leetcode-c-3sum/

Time complexity: O(n^2)

Leave a Reply