3Sum Closest

   找到与target最接近的三个数的和。

int three_sum_closest(vector<int> &num, int target) 
{
    int result = 0;
    int dist = INT_MAX;
    
    sort(num.begin(), num.end());
    
    for (vector<int>::const_iterator it = num.begin();
        it != num.end();
        ++it)
    {
        vector<int>::const_iterator front = it + 1;
        vector<int>::const_iterator back = num.end() - 1;
        
        while (front < back)
        {
            const int sum = *it + *front + *back;
            
            if (sum < target)
            {
                if (target - sum < dist)
                {
                    dist = target - sum;
                    result = sum;
                }
                
                ++front;
            }
            else if (sum > target)
            {
                if (sum - target < dist)
                {
                    dist = sum - target;
                    result = sum;
                }
                
                --back;
            }
            else
            {
                dist = 0;
                result = target;
                break;
            }
        }
    }
    
    return result;
}
posted @ 2012-08-30 15:17  紫红的泪  阅读(1507)  评论(0编辑  收藏  举报