您的位置:首页 > 产品设计 > UI/UE

find the closest sum to a target value

2014-08-27 03:35 633 查看
problem: given an array of integers including positive and negative, a target value. find 2 numbers in the array such that the sum of the 2 numbers is the closest to the target value.

Solution: this can be solved in O(nlogn).

First, invest some time to sort the array, O(nlogn).

Then,

int min= Integer.MAX;
while(i< j){
if(A[i]+ A[j]== T) return (i,j);
(A[i]+ A[j]- T> 0)? j--: i++;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐