https://oj.leetcode.com/problems/3sum-closest/
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,这道题就简单了。首先排序,然后只需用一个变量记录目前最接近的sum即可。由于题目given只有一个最接近的解,所以也无需考虑重复解的问题了。时间复杂度同样是O(n^2),代码如下。
public class Solution { public int threeSumClosest(int[] num, int target) { Arrays.sort(num); if(num.length == 0){ return 0; } int closestSum = num[0] + num[1] + num[2]; for(int i = 0; i < num.length - 2; i++){ int start = i + 1; int end = num.length - 1; while(start < end){ int sum = num[i] + num[start] + num[end]; if(sum == target){ return target; }else if (sum < target){ start++; if(Math.abs(sum - target) < Math.abs(closestSum - target)){ closestSum = sum; } }else if (sum > target){ end--; if(Math.abs(sum - target) < Math.abs(closestSum - target)){ closestSum = sum; } } } } return closestSum; } }