3Sum Closest in C++


Suppose we have an array nums with n integers and one target. We have to find three integers in nums such that the sum is closest to the target. We will return the sum of the three integers. We can take one assumption that each input would have exactly one solution. So if the given array is like [-1,2,1,-4] and the target is 1, then the triplet will be [-1,2,1] this has the closest sum, that is 2.

To solve this, we will follow these steps −

  • Sort the array nums, ans := 0, diff := Infinity, n := size of nums
  • for i in range 0 to n – 1
    • left := i + 1, right := n – 1
    • while left < right
      • temp := nums[left] + nums[right] + nums[i]
      • if |target – temp| < diff, then ans := temp and diff := |target – temp|
      • if temp = target, then return temp, otherwise when temp > target, then decrease right by 1, else increase left by 1
  • return ans

Example(C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int threeSumClosest(vector<int>& nums, int target) {
      sort(nums.begin(), nums.end());
      int ans = 0;
      int diff = INT_MAX;
      int n = nums.size();
      for(int i = 0; i < n; i++){
         int left = i + 1;
         int right = n - 1;
         while(left < right){
            int temp = nums[left] + nums[right] + nums[i];
            if(abs(target - temp) < diff){
               ans = temp;
               diff = abs(target - temp);
            }
            if(temp == target)return temp;
            else if(temp > target) right--;
            else left++;
         }
      }
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {-1,2,1,-4};
   cout << ob.threeSumClosest(v, 1);
}

Input

[-1,2,1,-4]
1

Output

2

Updated on: 27-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements