Trace nums = [-1, 2, 1, -4] with target = 1.
Sort: [-4, -1, 1, 2]. Initialize closest = -4 + (-1) + 1 = -4.
Fix -4 (index 0). Left at -1, right at 2:
- Sum =
-4 + (-1) + 2 = -3. Difference from1is4. Updateclosest = -3. - Sum < target, move left. Left at
1, right at2: - Sum =
-4 + 1 + 2 = -1. Difference is2. Updateclosest = -1.
Fix -1 (index 1). Left at 1, right at 2:
- Sum =
-1 + 1 + 2 = 2. Difference is1. Updateclosest = 2.
Fix 1 (index 2). Only one element right of it. Skip.
Return 2.
Outer loop: . Inner two-pointer: . Total: time, space.