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).3Sum的变种题,实际上就是枚举所有3Sum的情况,首先将数组排序,然后枚举第一个元素,之后用两个指针指向这个元素后面的数组部分,当三个数的和大于target的时候,移动右指针,因为这个时候再移动左指针只会让数变得更大,没有意义,小于target的时候,移动左指针,等于的时候直接返回就可以了。
public int threeSumClosest(int[] num, int target) { Arrays.sort(num); int best = num[0] + num[1] + num[2]; for(int i = 0; i < num.length-2; i++) { if(i != 0 && num[i-1] == num[i]) continue; int l = i+1, r = num.length-1; while(l < r) { int sum = num[i] + num[l] + num[r]; if(Math.abs(sum - target) < Math.abs(best - target)) { best = sum; } if(sum < target) { l++; while(l < num.length && num[l] == num[l-1]) l++; } else if(sum > target) { r--; while(r >= 0 && num[r] == num[r+1]) r--; } else return sum; } } return best; }
没有评论:
发表评论