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).
思路:借用上一题3Sum的思路,用n^2的时间复杂度去解决这个问题,只要在每次计算完sum之后比较一下是不是离target最近即可
package com.Ryan;
import java.util.Arrays;
public class Closest3Sum {
public static void main(String[] args) {
Closest3Sum closest3Sum=new Closest3Sum();
int[] nums= {-3,-2,-5,3,-4};
int target=-1;
System.out.println(closest3Sum.threeSumClosest(nums, target));
}
public int threeSumClosest(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 j=i+1,k=nums.length-1,sum;
while (j<k) {
sum=nums[i]+nums[j]+nums[k];
if (sum-target==0) {
return target;
}
else if (sum-target<0) {
j++;
}
else if (sum-target>0) {
k--;
}
if (Math.abs(sum-target)<Math.abs(result-target)) {
result=sum;
}
}
}
return result;
}
}