整体思路为将threeSum将为twoSum即可
public int solution(int[] nums, int target) { if (nums.length == 3) { return nums[0] + nums[1] + nums[2]; } else { Arrays.sort(nums); int r = 10000;//此两处10000为省事而设,如果严谨应该大致找到其中的一个较大距离 int distance = 10000; for (int i = 0; i < nums.length; i++) { int[] temarray = new int[nums.length - 1]; System.arraycopy(nums, 0, temarray, 0, i); System.arraycopy(nums, i + 1, temarray, i, nums.length - i - 1); int tem = twoSumClosest(temarray, target - nums[i]) + nums[i]; int temdistance = tem - target; if (temdistance < 0) { temdistance = -temdistance; } else if (temdistance == 0) { return tem; } if (temdistance < distance) { r = tem; distance = temdistance; } } return r; } } private int twoSumClosest(int[] nums, int target) { int l = 0, r = nums.length - 1; int min = nums[r] + nums[l]; int distance; if (min - target > 0) { distance = min - target; } else { distance = target - min; } while (l < r) { if (nums[l] + nums[r] == target) return nums[l] + nums[r]; if (nums[l] + nums[r] < target) { if (target - (nums[l] + nums[r]) < distance) { min = nums[l] + nums[r]; distance = target - (nums[l] + nums[r]); } l++; continue; } if (nums[l] + nums[r] > target) { if ((nums[l] + nums[r]) - target < distance) { min = nums[l] + nums[r]; distance = (nums[l] + nums[r]) - target; } r--; continue; } } return min; }
时间: 2024-10-19 09:59:10