16. 3Sum Closest

原创 2016年08月29日 22:42:39

枚举+二分搜索

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int n=nums.size();
        int i,j,k;
        int ans=nums[0]+nums[1]+nums[2];
        sort(nums.begin(),nums.end());
        
        for(i=0;i<=n-3;i++)
        {
            if(i>0&&nums[i]==nums[i-1])
                continue;
            for(j=i+1,k=n-1;j<k;)
            {
                if(j>i+1&&nums[j]==nums[j-1])
                {
                    j++;
                    continue;
                }
                if(k<n-1&&nums[k]==nums[k+1])
                {
                    k--;
                    continue;
                }
                int d=nums[i]+nums[j]+nums[k];
                if(d==target)
                    return d;
                else if(d>target)
                    k--;
                else
                    j++;
                if(abs(d-target)<abs(ans-target))
                    ans=d;
            }
        }
        return ans;
    }
};


《LeetBook》leetcode题解(16):3Sum Closest [M]

16. 3Sum Closest [M]Given an array S of n integers, find three integers in S such that the sum is cl...

LeetCode | 16. 3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given num...

LeetCode - 16. 3Sum Closest

方法一: 这一道题目自然也是有Brute Froce的解法,一开始思考的方法是通过三重循环和一个HashMap,分别记下来每种组合所对应的sum的大小,然后再从中找到与target最为接近的数返回。...

LeetCode --- 16. 3Sum Closest

题目链接:3Sum Closest Given an array S of n integers, find three integers in S such that the sum is clo...
  • makuiyu
  • makuiyu
  • 2015年01月30日 21:29
  • 671

#16 3Sum Closest

题目如下: Given an array S of n integers, find three integers in S such that the sum is closest to a gi...

leetcode16:3Sum Closest

3Sum Closest Given an array S of n integers, find three integers in S such that the sum is closes...
  • GODBAR
  • GODBAR
  • 2016年12月02日 20:15
  • 147

Leetcode 16. 3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given num...

16. 3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given num...

LeetCode No.16 3Sum Closest

LeetCode No.16 3Sum Closest

LeetCodet题解--16. 3Sum Closest(离给定值最近的三数之和)

链接 LeetCode题目:https://leetcode.com/problems/3sum-closest/ GitHub代码:https://github.com/gatieme...
  • gatieme
  • gatieme
  • 2016年04月04日 16:22
  • 1308
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:16. 3Sum Closest
举报原因:
原因补充:

(最多只允许输入30个字)