码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode:3sum closet

时间:2014-05-18 10:49:12      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:leetcode   优化   algorithm   c++   

题目:给一个数组和给定的目标值,要求在数组里找出三个元素,这三个元素的和最接近目标值,当然等于是最好的。

用3sum的方法,把判定条件作些修改。


int twoSum(vector<int> &num, int start, int target)
{
	if(num.size() < 3 || start >= num.size())
		return -target;
	int head = start;
	int tail = num.size() - 1;
	int result = -target;
	int erro = 0x7fffffff;
	while (head < tail)
	{
		int sum = num[head] + num[tail];
		if(sum == target)
			{
				result = target;
				return target;
		    }
		else if(sum < target){
			do 
			{
				++head;
			} while (head < tail && num[head] == num[head - 1]);
		}
		else
		{
			do 
			{
				--tail;
			} while (tail > head && num[tail] == num[tail + 1]);
		}
		int curerro = abs(sum - target);
		if(curerro < erro)
		{
			result = sum;
			erro = curerro;
		}
	}
	return result;
}
int threeSumClosest(vector<int> &num, int target) {
	const int len = num.size();
	if(len < 3)
		return 0;
	sort(num.begin(), num.end());
	int closet = -target;
	int erro = 0x7fffffff;
	for (int i = 0; i < len - 2; ++i)
	{
		int thisloop = twoSum(num, i + 1, target - num[i]);
		if(thisloop == target - num[i])
			return target;

		int cur_erro = abs(thisloop + num[i] - target);
	    if(cur_erro < erro)
		  {
			  closet = thisloop + num[i];
			  erro = cur_erro;
		}
		while(i + 1 < len && num[i + 1] == num[i])
 			++i;
	}
	return closet;
}


leetcode:3sum closet,布布扣,bubuko.com

leetcode:3sum closet

标签:leetcode   优化   algorithm   c++   

原文地址:http://blog.csdn.net/shiquxinkong/article/details/26007949

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!