1 topics
Given an array S of N integers, find three integers in S such 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).
2 Ideas
Well, after a few months did not brush, the problem did a very painful, spent 4, 5 hours. First of all, the problem of understanding the meaning of the wrong, and then understand the situation, the idea is wrong again. Have to look at other people's answers.
The best way to solve this problem is O (n^2).
Since the requirement of time complexity is O (n^2), then the idea is good to run. Traverse all 3 combinations to see which one is the closest to target. The method used is a head pointer, a tail pointer, a current pointer, details, see the code.
3 Code
Public intThreesumclosest (int[] Nums,inttarget) { intsum = 0; if(Nums.length <= 3) { for(inti:nums) {Sum+=i; } returnsum; } arrays.sort (Nums); Sum= Nums[0]+nums[1]+nums[2]; intAdd =sum; for(inti = 0; i < nums.length-2; i++) { intHead = i+1; intEnd = Nums.length-1; while(Head <end) {Add= Nums[i] + Nums[head] +Nums[end]; if(Add <target) {Head++; }Else{End--; } if(Math.Abs (Add-target) < Math.Abs (sum-target)) {Sum=add; } } } returnsum; }
Henceforth, as far as possible, two days one question.
[Leetcode] 3Sum Closest