16. 3Sum Closest (JAVA)
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).
class Solution { public int threeSumClosest(int[] nums, int target) { if(nums.length<3) return 0; int sum; int ret=nums[0]+nums[1]+nums[2]; //initialize return value int len = nums.length-2; int left; //point to the left side of the array int right; //point to the right side of the array Arrays.sort(nums); for(int i = 0; i < len; i++){ left = i+1; right = len+1; while(left < right){ sum = nums[i] + nums[left] + nums[right]; if(sum > target){ right--; } else if(sum < target){ left++; } else{ return target; } if(Math.abs(target - sum) < Math.abs(target - ret)) ret = sum; } //skip repeated digital while(nums[i] == nums[i+1]) { if(i+1 >= len) break; i++; } } return ret; } }