
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- 3Sum Smaller in C++
- 3Sum in Python
- Closest Divisors in C++
- Next Closest Time in C++
- Find K Closest Elements in C++
- Find the Closest Palindrome in C++
- Find closest number in array in C++
- Closest Binary Search Tree Value II in C++
- Find K Closest Points to the Origin in C++
- Find the closest and smaller tidy number in C++
- Sum of Mutated Array Closest to Target in C++
- Find closest value for every element in array in C++
- Find k closest numbers in an unsorted array in C++
- Find the closest leaf in a Binary Tree in C++
- Find the closest element in Binary Search Tree in C++

Advertisements