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。首先给数组排序,用两个变量分别记录当前最小距离和最近的和。代码如下,时间复杂度为O(n^2)
class Solution { public: int threeSumClosest(vector<int> &num, int target) { int len=num.size(); if(len<3){ return 0; } std::sort(num.begin(), num.end()); int closest=num[0]+num[1]+num[2]; int minDis = abs(closest-target); for(int i=0; i<len; i++){ int start=i+1, end=len-1; while(start<end){ int sum=num[i]+num[start]+num[end]; int dis=abs(sum-target); if(dis<minDis){ minDis=dis; closest=sum; } if(sum>target){ end--; }else{ start++; } } } return closest; } int abs(int a){ return a>=0?a:-a; } };
原文地址:http://blog.csdn.net/kangrydotnet/article/details/45149665