题目链接:https://leetcode.com/problems/3sum-closest/
题目:Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).题意:给定一个数组和一个target数,找出三个数使得他们的和最接近于target。
public class Solution
{
public int threeSumClosest(int[] nums, int target)
{
int length=nums.length;
int minNum=Integer.MAX_VALUE;
int tempsubNum=Integer.MAX_VALUE;
Arrays.sort(nums);
for(int i=0;i<length-2;i++)
{
//略过相同的数
if(i!=0&&nums[i]==nums[i-1])
{
continue;
}
int left=i+1;
int right=length-1;
while(left<right)
{
int a1=nums[left];
int a2=nums[right];
int sum=a1+a2+nums[i];
int subNum=Math.abs(sum-target);
//当前的和值sum离target更近一点
if(subNum<=tempsubNum)
{
tempsubNum=subNum; //保存这一步中的sum-target的差值
minNum=sum;
}
if(sum-target<0) //说明sum<target,要往右移动,使得sum变大才能更接近target
left++;
else//反之,往左移动
right--;
}
}
return minNum;
}
}