1 import java.util.Arrays;
2
3 public class Solution {
4 public static int threeSumClosest(int[] nums, int target) {
5 Arrays.sort(nums);
6 int length = nums.length;
7 int leftP;
8 int minT = nums[0] + nums[1] + nums[2] < target ? nums[0] + nums[1] + nums[2]: Integer.MIN_VALUE+1;
9 int maxT = nums[length-1] + nums[length-2] + nums[length-3] > target ? nums[length-1] + nums[length-2] + nums[length-3] : Integer.MAX_VALUE;
10 for(int i=0; i<length-2; i++){
11 // 最外层的去重方法
12 if(i>0 && nums[i]==nums[i-1]) {
13 continue;
14 }
15 leftP = i+1;
16 int rightP = length-1;
17 while(leftP<rightP) {
18 int temp = nums[i] + nums[leftP] + nums[rightP];
19 if (temp < target) {
20 minT = minT > temp ? minT : temp;
21 leftP += 1;
22
23 } else if (temp > target) {
24 maxT = maxT > temp ? temp : maxT;
25 rightP -= 1;
26 } else if (temp == target){
27 return target;
28 }
29 }
30 }
31 return ((long)maxT-target) > ((long)target-minT) ? minT : maxT;
32 }
33 }