Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3 sum closest #539

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions LeetCode/3Sum-Closest/Readme.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Question

Link - [3Sum Closest](https://leetcode.com/problems/3sum-closest/)
21 changes: 21 additions & 0 deletions LeetCode/3Sum-Closest/question.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to 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


Constraints:
3 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
-104 <= target <= 104
38 changes: 38 additions & 0 deletions LeetCode/3Sum-Closest/solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<int> v;

long int closest = INT_MAX;
bool found = false;
for(int i=0; i<nums.size(); i++) {

int left = i + 1;
int right = nums.size() - 1;
long int imt = 0;
while(left < right) {
imt = nums[i] + nums[left] + nums[right];
// closest = std::min(abs(imt-target), abs(closest-target));
if(abs(imt-target) < abs(closest-target)) {
closest = imt;
}
if(imt == target) {
found = true;
break;
}
if(imt < target) {
left++;
}
else {
right--;
}
}
if(found) {
break;
}
}

return closest;
}
};