您的位置:首页 > 编程语言 > Java开发

[LeetCode] 3Sum Closest

2014-11-17 13:50 309 查看
Given an array of 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).

Ideas: same with the 3sum, use two value to store the min difference and the min sum

public class Solution {
public int threeSumClosest(int[] num, int target) {
int minDiff = Integer.MAX_VALUE;
int minValue = Integer.MAX_VALUE;
int length = num.length;
Arrays.sort(num);

for(int i = 0; i < length - 2; i++)
{
int start = i + 1;
int end = length - 1;

while(start < end)
{
int sum = num[i] + num[start] + num[end];
int dif = Math.abs(sum - target);
if(dif == 0 ){
return target;
} else if(dif < minDiff){
minDiff = dif;
minValue = sum;
}

if(sum <= target){
start++;
}else{
end--;
}
}
}

return minValue;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode Java