3Sum Closest
Problem
Given an array S
of n
integers, find three integers in S
such that the sum is closest to a given number, target
. Return the sum of the three integers.
Example
For example, given array S = {-1 2 1 -4}
, and target = 1
. The sum that is closest to the target is 2
. (-1 + 2 + 1 = 2
).
Note
You may assume that each input would have exactly one solution.
Challenge
O(n^2)
time, O(1)
extra space.
Solution
Use 3 pointers:
- First sort the array (
O(n log n)
). Setmin
to the max of integer value. - Then for each position
i
, use aleft
pointer ati + 1
and aright
pointer atn - 1
.- Calculate the sum of the 3 positions, if it's absolute value is less than the current
min
value, updatemin
and remember thesum
. - if the
sum
is smaller than thetarget
, moveleft
to the right, otherwise moveright
to the left.
- Calculate the sum of the 3 positions, if it's absolute value is less than the current
- return the recorded
sum
.
The loops take O(n^2)
time, and the extra space is constant.