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简化为2Sum,采用从前和从后同时查找的方式进行搜索;
注意事项:优化,先排序后,对相邻相同数字的优化;其次对向前和向后相同数字的优化。
JAVA 代码:
- public int threeSumClosest(int[] num, int target) {
- int len = num.length;
- if(len<3) return 0;
- // float min = (float)Integer.MAX_VALUE;
- int min = num[0] + num[1] + num[2]; //注意min的选取
- Arrays.sort(num);
- for(int i=0;i<=len-3;i++) {
- if(i>0 && num[i] == num[i-1]) continue;
- int start = i+1;
- int end = len-1;
- while(start<end){
- if(num[start] + num[end] + num[i] == target) {
- return target;
- } else {
- if(Math.abs(num[start] + num[end] + num[i] - target) < Math.abs(min-target)) {
- min = num[start] + num[end] + num[i];
- }
- if(num[start] + num[end] + num[i] > target) {
- end--;
- while(end>=0 && num[end]==num[end+1]) end--;
- } else {
- start++;
- while(start<len&&num[start]==num[start-1]) start++;
- }
- }
- }
- }
- return min;
- }
未优化的C++代码:
- int threeSumClosest(vector<int> &num, int target) {
- if(num.size()<3) return 0;
- sort(num.begin(),num.end());
- int sz = num.size();
- int minSum = num[0]+num[1]+num[2];
- for(int i=0;i<sz-2;i++) {
- int tmp=num[i];
- int start = i+1;
- int end=sz-1;
- while(start<end) {
- int sum=tmp+num[start]+num[end];
- if(sum==target) return sum;
- if(abs(target-sum)<abs(minSum-target)) minSum= sum;
- if(sum>target) {
- end--;
- } else {
- start++;
- }
- }
- }
- return minSum;
- }

浙公网安备 33010602011771号