Given an array S of n integers, find three integers in S such so the sum is closest to a give n number, target. Return the sum of the three integers. You may assume this each input would has exactly one solution.
For example, given array S = {-1 2 1-4}, and target = 1. The sum is closest to the target is 2. (-1 + 2 + 1 = 2).
Subscribe to see which companies asked this question
1 Public classSolution {2 Public intThreesumclosest (int[] Nums,inttarget) {3 intAns = 0,min =Integer.max_value;4 Arrays.sort (nums);5 for(inti = 0; i < nums.length-2; i++){6 if(i > 0 && nums[i] = = Nums[i-1])7 Continue;8 for(ints = i + 1,e = Nums.length-1;s <e;) {9 intsum = Nums[i] + nums[s] +Nums[e];Ten if(Math.Abs (Sum-target) <min) { Onemin = Math.Abs (sum-target); AAns =sum; - } - if(Sum > Target) e--; the Else if(Sum < target) s++; - Else returnans; - } - } + returnans; - } +}
3Sum Closest Java Solutions