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.
nums and target?
nums can contain both positive and negative integers. The value of n (number of elements in nums) can vary but is generally within the range of 3 to 1000. The target can also be any integer.nums contain duplicate numbers?
nums can contain duplicate numbers.To solve the problem effectively, we can follow these steps:
def threeSumClosest(nums, target):
nums.sort()
n = len(nums)
closest_sum = float('inf') # Initialize with infinity
for i in range(n - 2):
left = i + 1
right = n - 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
# Update closest_sum if current_sum is closer to target
if abs(current_sum - target) < abs(closest_sum - target):
closest_sum = current_sum
if current_sum < target:
left += 1
elif current_sum > target:
right -= 1
else:
# If the sum is exactly equal to the target, return it
return target
return closest_sum
# Example usage
nums = [-1, 2, 1, -4]
target = 1
print(threeSumClosest(nums, target)) # Output: 2
Therefore, the overall time complexity is (O(n^2)) due to the nested loop and two-pointer combination, which is efficient for the given constraints.
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?