Question
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Solution
和3Sum的思路基本一样。也是固定起点后,双指针遍历。
1 public class Solution { 2 public int threeSumClosest(int[] nums, int target) { 3 if (nums == null || nums.length < 3) { 4 return 0; 5 } 6 int length = nums.length; 7 Arrays.sort(nums); 8 int min = Integer.MAX_VALUE; 9 int result = nums[0] + nums[1] + nums[2]; 10 for (int i = 0; i < length - 2; i++) { 11 // Avoid duplicates 12 if (i > 0 && nums[i] == nums[i - 1]) { 13 continue; 14 } 15 int l = i + 1, r = length - 1; 16 while (l < r) { 17 int sum = nums[i] + nums[l] + nums[r]; 18 int sub = Math.abs(sum - target); 19 if (sub == 0) { 20 return sum; 21 } else if (min > sub) { 22 min = sub; 23 result = sum; 24 } 25 if (sum > target) { 26 r--; 27 // Avoid duplicates 28 while (l < r && nums[r] == nums[r + 1]) { 29 r--; 30 } 31 } else if (sum < target) { 32 l++; 33 // Avoid duplicates 34 while (l < r && nums[l] == nums[l - 1]) { 35 l++; 36 } 37 } 38 } 39 } 40 return result; 41 } 42 }
时间: 2024-11-07 23:07:02