码迷,mamicode.com
首页 > 其他好文 > 详细

find the closest sum to a target value

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

标签:style   blog   color   os   io   ar   div   log   sp   

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

标签:style   blog   color   os   io   ar   div   log   sp   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!