标签:
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers.
You may assume that each input would have exactly one solution.
For example, given array S = [-1 2 1 -4]
, and target = 1
. The sum that is closest to the target is 2
. (-1 + 2 + 1 = 2).
1 public class Solution { 2 /** 3 * @param numbers: Give an array numbers of n integer 4 * @param target : An integer 5 * @return : return the sum of the three integers, the sum closest target. 6 */ 7 public int threeSumClosest(int[] num ,int target) { 8 int tempClosestSum = Integer.MAX_VALUE; 9 int diff = Integer.MAX_VALUE; 10 if(num == null || num.length < 3) { 11 return tempClosestSum; 12 } 13 Arrays.sort(num); 14 for (int i = 0; i < num.length - 2; i++) { 15 if (i != 0 && num[i] == num[i - 1]) { 16 continue; // to skip duplicate numbers; e.g [0,0,0,0] 17 } 18 19 int left = i + 1; 20 int right = num.length - 1; 21 while (left < right) { 22 int sum = num[left] + num[right] + num[i]; 23 if (sum - target == 0) { 24 return target; 25 } else if (sum - target < 0) { 26 if (Math.abs(sum - target) < Math.abs(tempClosestSum - target)) { 27 tempClosestSum = sum; 28 } 29 left++; 30 } else { 31 if (Math.abs(sum - target) < Math.abs(tempClosestSum - target)) { 32 tempClosestSum = sum; 33 } 34 right--; 35 } 36 } 37 } 38 return tempClosestSum; 39 } 40 }
转载请注明出处: cnblogs.com/beiyeqingteng/
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5639698.html