

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
#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
- Related Questions & Answers
- 3Sum in Python
- 3Sum Smaller in C++
- Closest Divisors in C++
- Next Closest Time in C++
- jQuery closest() with Example
- Find K Closest Elements in C++
- Find the Closest Palindrome in C++
- Index of closest element in JavaScript
- Closest Pair of Points Problem
- Find closest number in array in C++
- Find closest index of array in JavaScript
- Closest Binary Search Tree Value II in C++
- Program to find closest dessert cost in Python
- Program to find closest subsequence sum in Python
- Get closest number out of array JavaScript
Advertisements