[LeetCode] 3Sum Closest

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

二次刷题(2015-08-18)

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int len = nums.size();
        if(len < 3){
            return 0;
        }
        std::sort(nums.begin(), nums.end());
        int minDis = INT_MAX;
        int result = nums[0] + nums[1] + nums[2];
        for(int i = 0; i<len; i++){
            int start = i + 1, end = len - 1;
            while(start < end){
                int sum = nums[i] + nums[start] + nums[end];
                int dis = abs(sum - target);
                if(dis < minDis){
                    result = sum;
                    minDis = dis;
                }
                if(sum < target){
                    start++;
                }else{
                    end--;
                }
            }
        }
        return result;
    }
};


0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注