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
原创粉丝点击