leetcode--3Sum Closest

1.题目描述

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).

2.解法分析

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

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;
        
    }
};
posted @ 2013-08-22 18:17  曾见绝美的阳光  阅读(649)  评论(0编辑  收藏  举报