首页 > 其他 > 详细

[LeetCode] 3Sum Closest

时间:2015-04-20 14:55:05      阅读:164      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!