method One:
This topic naturally also has brute FROCE solution, the first way to think is through the triple loop and a hashmap, respectively, write down each combination of the sum corresponding to the size, and then find the closest to the target number returned. The time complexity of this method is very high, for O (n^3), plus hashmap and compare the size of the time spent in Leetcode OJ above almost certainly to time out, so the detailed code will not write
Method Two:
Thinking about the 3Sum topic that we've done before, in this topic, we iterate through each number in the array through an outer loop, then set two pointers to the head and tail, respectively, to the remainder of the array in each outer loop, and then locate the target by moving two pointers. This topic is very similar to the 3Sum, we can consider the same idea, but notice that there are also changes in this topic, first of all, we are not to look for target, but to find the smallest difference with target number, this is a common problem, you can set an initial value of integer, Max_value the number of flags, each difference to be resolved by comparison, the other is that what is needed here is just a figure, do not have to find all the combination, so in the answer does not need to test the repetition of the elements in the array
public class Solution {public int threesumclosest (int[] nums, int target) {//sort array arrays.sor
T (nums);
int result = 0;
int Pfront;
int pback;
max value int diff = integer.max_value;
for (int i = 0; i < nums.length-2; i++) {//set pointers Pfront = i + 1;
Pback = nums.length-1;
while (Pfront < pback) {int sum = Nums[i] + Nums[pfront] + nums[pback];
if (sum = = target) {return target; }else if (Math.Abs (Target-sum) < diff) {//update closest Value and diff diff
= Math.Abs (target-sum);
result = SUM;
}//move Pointers if (sum < target) {pfront++;
}else{ pback--;
}}} return result; }
}
Knowledge Points:
1. Integer.max_value, Integer.min_value;
2. Finding a number that is different from a number is a common sub-problem, you can set a flag amount, set its initial value to maximum or minimum, and then get a comparison of each result, according to the situation update