3Sum Closest
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
1 public int threeSumClosest(int[] nums, int target) { 2 Arrays.sort(nums); 3 int sum = nums[0] + nums[1] + nums[2]; 4 int diff = Math.abs(sum - target); 5 for (int i = 0; i < nums.length - 2; i++) { 6 if (i != 0 && nums[i] == nums[i - 1]) 7 continue; 8 int j = i + 1; 9 int k = nums.length - 1; 10 while (k > j) { 11 int aa = nums[i] + nums[j] + nums[k]; 12 int newDiff = Math.abs(aa - target); 13 if (newDiff < diff) { 14 diff = newDiff; 15 sum = aa; 16 } 17 if (aa < target) { 18 j++; 19 } else { 20 k--; 21 } 22 } 23 } 24 return sum; 25 }