首页 > 代码库 > find the closest sum to a target value
find the closest sum to a target value
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。