Two Sum Closest to K
2015-01-31 05:47
309 查看
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--;
else
start++;
}
return result;
}
Return [-83, 85]
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--;
else
start++;
}
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]
相关文章推荐
- Two Sum - Closest to target
- leetocode371 Sum of Two Integers
- To find sum of two numbers without using any operator. Only use of printf() is allowed.
- LeetCode之“散列表”:Two Sum && 3Sum && 3Sum Closest && 4Sum
- Two Sum - Difference equals to target
- find the closest sum to a target value
- Distribute numbers to two “containers” and minimize their difference of sum
- LintCode Two Sum Closest
- I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum o
- 【NO.3】 c program to caculate and display sum of two matrix
- Leetcode 1. Two Sum & 15. 3Sum & 16. 3Sum Closest & 18. 4Sum
- 【NO.3】 c program to caculate and display sum of two matrix
- Two Sum & 3Sum & 3Sum Closest & 4Sum
- LeetCode :: Sum Root to Leaf Numbers [tree、dfs]
- LeetCode 第 371 题 (Sum of Two Integers)
- LeetCode | Sum Root to Leaf Numbers
- LeetCode:Two Sum III - Data structure design
- 【leetcode】1. Two Sum(Python & C++)
- LeetCode OJ:Sum Root to Leaf Numbers
- LeetCode编程练习 - Two Sum学习心得