码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode第16题--3Sum Closest

时间:2014-10-17 13:33:42      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   sp   div   

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

吃饭之前刷了这题。思路就是和上题类似。先srot,然后固定i从第一个到倒数第三个,然后设一个left=i+1,right=num.size()-1; 如果三个数相加和target相比较大,那就right--,使三个数相加要变小。如果比target小那就left++。同时用abs记录当前的差值,如果比之前的差值更小,那就记录三个数的和到val中。如果差值为零了,那就直接返回三个数的和。否则到最后在返回val就可以了。代码如下
class Solution {
public:
int threeSumClosest(vector<int> &num, int target)
{
    int left = 0, right = 0, val = 0, minC = INT_MAX;
    sort(num.begin(), num.end());
    for (int i = 0; i < num.size() - 2; ++i)
    {
        left = i + 1; right = num.size() - 1;
        while(left < right)
        {
            int tepVal = target - num[i] - num[left] - num[right];
            if (abs(tepVal) < minC)
                {minC = abs(tepVal); val = num[i] + num[left] + num[right];}
            if (tepVal > 0)
                left++;
            else if (tepVal < 0)
                right--;
            else
                return num[i] + num[left] + num[right];
        }
    }
    return val;
}
};

吃饭去了。

leetcode第16题--3Sum Closest

标签:style   blog   color   io   os   ar   for   sp   div   

原文地址:http://www.cnblogs.com/higerzhang/p/4030769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!