Title: https://leetcode.com/problems/3sum-closest/
"Label" Array; Pointers
"Personal Analysis"
This question and its sister problem 3Sum very similar, will not say more, specific analysis can refer to [leetcode][015] 3Sum
1 Public classSolution {2 Public intThreesumclosest (int[] Nums,inttarget) {3 intresult =Target;4 intLen =nums.length;5 if(Len < 3) {6 return0;7 }8 Arrays.sort (nums);9 for(inti = 0; i < Len; i++) {Ten intNumber =Nums[i]; One A intLeftindex = i + 1; - intRightindex = len-1; - while(Leftindex <Rightindex) { the intThreesum = number + Nums[leftindex] +Nums[rightindex]; - if(Threesum = =target) { - //Best result found! - returnTarget; +}Else { - //Update Global Result + if(Result = = Target | | AMath.Abs (Target-threesum) < Math.Abs (Target-result)) { atresult =threesum; - } - if(Threesum <target) { - while(Leftindex < Rightindex && -Nums[leftindex] = = Nums[leftindex + 1]) { -leftindex++; in } -leftindex++; to}Else { + while(Leftindex < Rightindex && -Nums[rightindex] = = Nums[rightindex-1]) { therightindex--; * } $rightindex--;Panax Notoginseng } - } the } + } A returnresult; the } + -}
[Leetcode] [016] 3Sum Closest (Java)