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

[LeetCode] 3Sum Closest

时间:2015-04-20 14:58:00      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

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;
    }
};


[LeetCode] 3Sum Closest

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/45149665

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