LeetCode Q 16 - 3Sum Closest
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:Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Solution
Code:
public int threeSumClosest(int[] nums, int target) {
int res = 0, diff = Integer.MAX_VALUE;
int len = nums.length;
Arrays.sort(nums);
for (int i = 0; i < len - 2; i++) {
if (i != 0 && nums[i] == nums[i - 1]) continue;
int l = i + 1, r = len - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
if (Math.abs(sum - target) < diff) {
diff = Math.abs(sum - target);
res = sum;
}
if (sum > target)
r--;
else if (sum < target)
l++;
else if (sum == target)
return target;
}
}
}