首页 > 其他 > 详细

find the closest sum to a target value

时间:2014-08-27 03:53:57      阅读:284      评论:0      收藏:0      [点我收藏+]

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++;     
}

 

find the closest sum to a target value

原文:http://www.cnblogs.com/miaoz/p/3938578.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!