您的位置:首页 > 其它

leetcode--3Sum Closest

2013-08-22 18:17 253 查看
1.题目描述

[code]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).

[/code]



2.解法分析


关于这个题目的解法一个共识就是需要排序,由于有三个数需要考虑,最简单的办法自然事件复杂度为O(N3),所以排序的复杂度可以忽略,排完序之后,可以得到一个O(N2)的算法。

[code]class Solution {


public:


int threeSumClosest(vector<int> &num, int target) {


// Start typing your C/C++ solution below


// DO NOT write int main() function


int numSize = num.size();


if(numSize<3)return -1;




sort(num.begin(),num.end());


int minMargin=num[0]+num[1]+num[2]-target;




int curMargin=0;


for(int i=0;i<=numSize-3;++i)


{


    int j;int k;


    for(j=i+1,k=numSize-1;j<k;)


    {


curMargin=num[i]+num[j]+num[k]-target;


if(curMargin==0)return target;


if(abs(curMargin)<abs(minMargin))minMargin=curMargin;  


if(curMargin<0)j++;


else k--;    


}


}


return minMargin+target;




}


};

[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: