您的位置:首页 > 其它

三数之和 II——LintCode

2015-12-11 13:02 501 查看
给一个包含n个整数的数组S, 找到和与给定整数target最接近的三元组,返回这三个数的和。

您在真实的面试中是否遇到过这个题?

Yes

样例

例如S = [-1, 2, 1, -4] and target = 1. 和最接近1的三元组是 -1
+ 2 + 1 = 2.

注意

只需要返回三元组之和,无需返回三元组本身

public class Solution {
/**
* @param numbers: Give an array numbers of n integer
* @param target : An integer
* @return : return the sum of the three integers, the sum closest target.
*/
public int threeSumClosest(int[] numbers ,int target) {
// write your code here

int min = Integer.MAX_VALUE, re=0;
for(int i=0;i<numbers.length;i++)
for(int j=i+1;j<numbers.length;j++)
for(int k=j+1;k<numbers.length;k++)
{
int x = numbers[i] + numbers[j] + numbers[k] - target;
if(x == 0)
return target;
if(x < 0)
{
x = -x;
if(x < min )
{
min = x;
re = -x + target;
}
}
else {
if(x < min )
{
min = x;
re = x + target;
}
}
}
return re;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: