similar with 3Sum
1 public class Solution { 2 public int threeSumClosest(int[] num, int target) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 if(num == null || num.length < 3) 6 return 0; 7 Arrays.sort(num); 8 int result = num[0] + num[1] + num[2]; 9 for(int i = 0; i < num.length - 2; i++){ 10 int start = i + 1; 11 int end = num.length - 1; 12 while(start < end){ 13 int tmp = num[start] + num[end] + num[i]; 14 if(Math.abs(tmp - target) < Math.abs(result - target)) 15 result = tmp; 16 if(tmp == target) 17 return target; 18 else if(tmp < target) 19 start++; 20 else 21 end--; 22 } 23 } 24 return result; 25 } 26 }