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
class Solution {
public int threeSumClosest(int[] nums, int target) {
int temp = Integer.MAX_VALUE;
int tempData = Integer.MIN_VALUE;
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
int lo = i + 1;
int lh = nums.length - 1;
while (lo < lh) {
int sum = nums[lo] + nums[lh];
int allNumber = sum + nums[i];
if (allNumber == target) {
return target;
}
int i1 = target - allNumber;
if (Math.abs(i1) < temp) {
temp = Math.abs(i1);
tempData = allNumber;
}
if (allNumber < target) {
lo++;
} else {
lh--;
}
}
}
return tempData;
}
}