Two Sum Closest to K
来源:互联网 发布:淘宝教育怎么入驻 编辑:程序博客网 时间:2024/06/04 19:06
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--;elsestart++;}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]
0 0
- Two Sum Closest to K
- LintCode Two Sum Closest
- Two Sum & 3Sum & 3Sum Closest & 4Sum
- Two Sum,3Sum,3Sum Closest,4Sum
- 3sum closest to target
- [leetcode][two pointers][大数] 3Sum Closest
- LeetCode 16. 3Sum Closest (Two-Pointer)
- K closest points to a given point
- K closest point to the origin
- 【leetcode X Sum 系列】Two Sum|3Sum|3Sum Closest|4Sum
- LeetCode (1) Two Sum (15)Three sum (16)Three sum closest (17)Four sum
- 程序员面试题目总结--数组(27)【Two Sum 、3Sum、3Sum Closest 、4Sum】
- LeetCode1/16/15/18 Two Sum/3Sum/3Sum Closest/4Sum**
- Leetcode 1. Two Sum & 15. 3Sum & 16. 3Sum Closest & 18. 4Sum
- 第五周:[leetcode] Two Sum、3Sum、3Sum Closest、4Sum
- leetcode 1|167.two sum 1|2 && 3.three sum && 16.3Sum Closest && 18. 4Sum
- *LeetCode 3sum 3sum-closest 4sum k-sum类型 总结【待解决证明问题】
- Submatrix Sum equals to K
- DevCon 命令行实用工具可替代设备管理器
- HTML5 声明兼容IE的写法
- 养成定时更新内容的好习惯,提高搜索引擎时效性收录
- lv官方網 wqdx axsr jguq
- 最大子列和问题
- Two Sum Closest to K
- django提交表单提示"You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SL
- 403-In general, this can occur when there is a genuine Cross Site Request Forgery, or whe
- 我们可以推测矩阵乘法最优解的时间复杂度么?
- 自制CPU一开山篇
- Codeforces Round #288 (Div. 2)
- url规则
- 关于xcode 6.0+上 iOS8.0+ 模拟器不弹出虚拟键盘和没有中文输入法的解决方案
- android:onClick 的使用 xml调用Java代码