您的位置:首页 > 其它

Two Sum Closest to K

2015-01-31 05:47 309 查看
An Array of integers is given, both +ve and -ve. You need to find the two elements such that their sum is closest to target.

public static int[] findTwoSumClosest(int[] num, int target) {
if(num==null || num.length==0)
return null;
int[] result = new int[2];
Arrays.sort(num);
int start=0, end=num.length-1;
int closest = Integer.MAX_VALUE;
while(start<end){
int sum = num[start] + num[end];
int diff = Math.abs(target-sum);
if(diff<closest){
closest = diff;
result[0] = num[start];
result[1] = num[end];
}
if(sum>target)
end--;
else
start++;
}
return result;
}
public static void main(String[] args) {

int[] num = {1,60,-10,70,-80,85,95,79,-83};

int[] result = findTwoSumClosest(num,3);
System.out.print(result[0]+"  "+result[1]);

}


Return  [-83, 85]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Two Sum Array