LeetCode OJ 之 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.

给定一个含有n个整数的数列,找出三个数,使得它们三个的和与给定的数target的差值的距离最小。返回符合条件的三个数的和。你可以假定每个输入都有一个结果。

    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).

思路:

参考前一篇求三个数的和的思路:http://blog.csdn.net/u012243115/article/details/41361781

代码:

class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) 
    {
    	int pre = 0x7fffffff;
    	int result = 0;//保存三个数的和
    	sort(num.begin(),num.end());//先对数组排序
    	int len = num.size();
    	if(len < 3)
    		return 0;
    	for(int i = 0 ; i < len ; i++)
    	{
    		if( i > 0 && num[i] == num[i-1])
    		{
    			continue;//如果重复,则跳到下一个,一定要结束本次循环,重新进行判断
    		}
    		for(int j = i + 1 , k = len - 1 ; j < k ; )
    		{
    			if(j > i+1 && num[j] == num[j-1])
    			{
    				j++;
    				continue;
    			}
    			if(k < len - 1 && num[k] == num[k+1])
    			{
    				k--;
    				continue;
    			}
    			int cur = num[i] + num[j] + num[k];
    			int gap = cur - target > 0 ? cur - target : target - cur;//差值
    			
    			//如果差值比之前的小,则保存当前的三个数和到result
    			if(gap < pre)
    			{
    				pre = gap;
    				result = cur;
    			}
    			//判断当前三个数的和与target的大小,决定j和k的移动方向
    			if(cur < target)
    				j++;
    			else
    				k--;
    		}
    	}
    	return result;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值