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).
/**
* 暴力破解 O(n*n*n)
* 通过遍历,每次获取三个数的和,并且与target作差,取其绝对值,每次循环获取差值最小的三个数,放入listzho中
* @param nums
* @param target
* @return
*/
public static int threeSumClosest1(int[] nums, int target)
{
List<Integer>list = new ArrayList<>();
int result = Integer.MAX_VALUE;
int temp = 0;
for(int i = 0; i < nums.length-2; i++)
{
for(int j = i+1; j < nums.length-1;j++)
{
for(int k = j+1; k < nums.length; k++)
{
int sum = (nums[i] + nums[j] + nums[k]);
temp = Math.abs(sum - target);
if(temp < result)
{
result = temp;
list.clear();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[k]);
}
}
}
}
return (list.get(0)+list.get(1)+list.get(2));
}
/**
* 暴力破解改进 O(n*n)
* @param nums
* @param target
* @return
*/
public static int threeSumClosest2(int[] nums, int target)
{
int result = nums[0] + nums[1] + nums[nums.length - 1];
Arrays.sort(nums);
for(int i = 0; i< nums.length - 2;i++)
{
int start = i+1;
int end = nums.length - 1;
while(start < end)
{
int sum = nums[i]+ nums[start] + nums[end];
if(sum > target)
{
end--;
}
else
{
start++;
}
if(Math.abs(sum-target) < Math.abs(result - target))
{
result = sum;
}
}
}
return result;
}