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).
Q: Can the array contain duplicate integers? A: Yes, the array can contain duplicates.
Q: Should the solution handle large arrays efficiently? A: Yes, the solution should be efficient enough to handle reasonably large arrays as per typical LeetCode constraints.
Q: Are there any constraints on the values of integers in nums
, such as minimum or maximum values?
A: No specific constraints aside from standard integer limits.
left
and right
) to find the pair that, along with the selected element, gives the closest sum to the target.
left
to the element next to the current element and right
to the last element.import java.util.Arrays;
public class ThreeSumClosest {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int closestSum = nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums.length - 2; i++) {
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int currentSum = nums[i] + nums[left] + nums[right];
if (Math.abs(currentSum - target) < Math.abs(closestSum - target)) {
closestSum = currentSum;
}
if (currentSum < target) {
left++;
} else if (currentSum > target) {
right--;
} else {
// if the currentSum is exactly equal to the target, it's the closest possible sum
return currentSum;
}
}
}
return closestSum;
}
// For Testing
public static void main(String[] args) {
ThreeSumClosest solver = new ThreeSumClosest();
int[] nums = {-1, 2, 1, -4};
int target = 1;
int result = solver.threeSumClosest(nums, target);
System.out.println(result); // Output should be 2
}
}
O(n log n)
.O(n^2)
in the worst case.
Thus, the overall time complexity of the algorithm is O(n^2)
.
O(n^2)
, which is efficient for the given problem.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?