ITPub博客

首页 > > > [LeetCode] 3Sum Closest

[LeetCode] 3Sum Closest

作者:Ruiyuan Li 时间:2015-04-20 00:00:00 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 &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; itarget){
                    end--;
                }else{
                    start++;
                }
            }
        }
        return closest;
    }
    
    int abs(int a){
        return a>=0?a:-a;
    }
};

二次刷题(2015-08-18)

class Solution {
public:
    int threeSumClosest(vector& 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


转载请注明: » [LeetCode] 3Sum Closest
<!-- -->

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4826