#16
Medium Algorithms 3sum closest
Array Two Pointers Sorting
48.1% acceptance
Jan 12, 2026
11563
618
Given an integer array nums of length n and an integer target, find three integers at distinct indices 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.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn three_sum_closest(nums: Vec<i32>, target: i32) -> i32 {
let mut nums = nums;
nums.sort();
let n = nums.len();
let mut closest_sum = nums[0] + nums[1] + nums[2];
for i in 0..n-2 {
let mut left = i + 1;
let mut right = n - 1;
while left < right {
let sum = nums[i] + nums[left] + nums[right];
if (sum - target).abs() < (closest_sum - target).abs() {
closest_sum = sum;
}
if sum < target {
left += 1;
} else if sum > target {
right -= 1;
} else {
return sum;
}
}
}
closest_sum
}
}