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.
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
import java.util.*;
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int sum = 0;
boolean firstFlag = true;
for(int i = 0; i < nums.length-2; i++) {
int j = i+1;
int k = nums.length-1;
while(j<k){
int tmpSum = nums[i]+nums[j]+nums[k];
if(firstFlag == true){
sum = tmpSum;
firstFlag = false;
}else if(Math.abs(target-sum)>Math.abs(target-tmpSum)){
sum = tmpSum;
}
if(tmpSum==target){
return target;
}else if(tmpSum > target){
k--;
}else{
j++;
}
}
}
return sum;
}
}
原文:https://www.cnblogs.com/clnsx/p/12240790.html