3 Sum Closest

3 Sum Closest

Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to the target.

Return the sum of the three integers.

You may assume that each input would have exactly one solution.

Example 1:

Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). Example 2:

Input: nums = [0,0,0], target = 1 Output: 0

In this problem, we have to use sorting, binary search, and 2 pointers approach first by looping through the array after sorting i is the first pointer then inside the loop lo and hi are the 2 pointers which give us 3 indexes for sum comparisons.

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {

        sort(nums.begin(),nums.end());
        int error=INT_MAX,res=0,n=nums.size()-1;
        for(int i=0;i<n;i++)
        {
            int lo=i+1,hi=n;
            while(lo<hi)
            {
                int sum=nums[i]+nums[lo]+nums[hi];
                int diff=abs(target-sum);
                if(diff<error)
                {
                    error=diff;
                    res=sum;
                }
                if(diff==0) return sum;
                if(sum>target) hi--;
                else lo++;
            }
        }
        return res;

    }
};

Time complexity: for sorting O(NlogN) + for iterating O(N^2)= O(N^2)