Title Description:
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).
Problem Solving Ideas:
This is similar to the idea of 3Sum, but the process of implementation is much simpler. Outside a large loop, which is also starting from both sides, if the sum of the three numbers minus the absolute value of the target is smaller, update it and record the sum of the three numbers.
The code is as follows:
1 Public classSolution {2 Public intThreesumclosest (int[] Nums,inttarget) {3 intLength =nums.length;4 intMin =Integer.max_value;5 intLeft, right, comp, result = 0;6 7 if(Length < 3)8 return0;9 Arrays.sort (nums);Ten One for(inti = 0; i < length-2; i++) { Aleft = i + 1; -right = Length-1; - while(Left <Right ) { thecomp = Nums[i] + nums[left] +Nums[right]; - if(Math.Abs (Comp-target) <min) { -min = Math.Abs (Comp-target); -result =comp; + } - if(Comp >target) +right--; A Else if(Comp <target) atleft++; - Else - returnTarget; - } - } - returnresult; in } -}
Given an array S of n integers, find three integers in S such so the sum is closest to A given 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).
Java [Leetcode] 3Sum Closest