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.
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).
思路和3 Sum基本一致,稍微有点变化而已。
public class Solution { /** * @param numbers: Give an array numbers of n integer * @param target : An integer * @return : return the sum of the three integers, the sum closest target. */ public int threeSumClosest(int[] numbers ,int target) { // write your code here if(numbers == null || numbers.length == 0) return target; Integer result = null; Integer diff = null; Arrays.sort(numbers); for(int i = 0; i < numbers.length - 2; i++){ if(i > 0 && numbers[i] == numbers[i - 1]) continue; int left = i + 1; int right = numbers.length - 1; while(left < right){ if(result == null){ result = numbers[i] + numbers[left] + numbers[right]; diff = Math.abs(numbers[i] + numbers[left] + numbers[right] - target); } if(Math.abs(numbers[i] + numbers[left] + numbers[right] - target) < diff){ result = numbers[i] + numbers[left] + numbers[right]; diff = Math.abs(numbers[i] + numbers[left] + numbers[right] - target); } if(numbers[i] + numbers[left] + numbers[right] < target){ left++; while(left < right && numbers[left] == numbers[left - 1]) left++; } else if(numbers[i] + numbers[left] + numbers[right] > target){ right--; while(left < right && numbers[right] == numbers[right + 1]) right--; } else return target; } } return result; } }
时间: 2024-10-13 02:33:22