classSolution{ publicintthreeSumClosest(int[] nums, int target){ //数组排序 Arrays.sort(nums); //返回结果 int result = 0; //表示当前最小差 int distance = Integer.MAX_VALUE; for (int i=0; i < nums.length; i++) { //两个指针 int left = i + 1; int right = nums.length - 1;
while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum < target) { //说明left需要后移 if (target - sum < distance) { distance = target - sum; result = sum; } //left右移 left ++; } elseif (sum > target) { if (sum - target < distance) { distance = sum - target; result = sum; } right --; } else { return target; } } } return result; } }