public int threeSumClosest(int[] nums, int target) { int n = nums.length; Arrays.sort(nums); int threeAns = nums[0] + nums[1] + nums[2]; for (int i = 0; i < n; i++) { int left = i + 1; int right = n - 1; while(left < right){ int sum = nums[i] + nums[left] + nums[right]; if (Math.abs(threeAns - target) > Math.abs(sum - target)){ threeAns = sum; } if(sum > target){ right--; }else if(sum < target){ left++; }else{ return threeAns; } } } return threeAns; }
原文:https://www.cnblogs.com/tqw1215/p/13388126.html