Given an array nums
of n
integers 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:
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).
n
(size of nums)?nums
?target
than the previously recorded closest sum, update the closest sum.current_sum == target
), you can immediately return because you can’t get closer than an exact match.#include <vector>
#include <algorithm>
#include <cstdlib> // for abs()
using namespace std;
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int closestSum = nums[0] + nums[1] + nums[2]; // Initial assumption with first three elements
for (size_t i = 0; i < nums.size() - 2; ++i) {
size_t left = i + 1;
size_t right = nums.size() - 1;
while (left < right) {
int currentSum = nums[i] + nums[left] + nums[right];
// Update the closestSum if the currentSum is closer to the target
if (abs(currentSum - target) < abs(closestSum - target)) {
closestSum = currentSum;
}
if (currentSum < target) {
++left;
} else if (currentSum > target) {
--right;
} else {
// If currentSum equals target, we've found the closest possible sum
return currentSum;
}
}
}
return closestSum;
}
};
Thus, the overall time complexity is (O(n^2)), where (n) is the size of the input array nums
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?