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

[LeetCode]3 Sum Closet

时间:2014-10-17 00:28:43      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:blog   io   os   ar   for   sp   div   on   log   

// 3SumClosest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <vector>
#include<cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
class Solution {
public:
	int threeSumClosest(vector<int> &num, int target) {
		int closet = 999999;
		sort(num.begin(),num.end());
		for (int i = 0; i < num.size()-2; i++)
		{
			if (i>0 && num[i] == num[i - 1])
				continue;
			int p1 = i + 1, p2 = num.size() - 1;
			while (p1 < p2)
			{
				if (p1>i + 1 && num[p1] == num[p1 - 1])
				{
					p1++;
					continue;
				}
				if (p2 < num.size() - 1 && num[p2] == num[p2 + 1])
				{
					p2--;
					continue;
				}
				if (p1>p2)
					break;
				int sum = num[i] + num[p1] + num[p2];
				
				if (sum == target)
				{
					p2--;
					closet = target;
				}
				else if (sum<target)
				{
					p1++;
					if (abs(sum - target) < abs(closet - target))
					{
						closet = sum;
					}
				}
				else
				{
					p2--;
					if (abs(sum - target) < abs(closet - target))
					{
						closet = sum;
					}
				}
			}
		}
		return closet;
	}
};
int _tmain(int argc, _TCHAR* argv[])
{
	Solution ss;
	vector<int>test;
	test.push_back(1);
	test.push_back(1);
	test.push_back(1);
	test.push_back(0);
	//test.push_back(-4);
	int sum = ss.threeSumClosest(test,100);
	cout << sum << endl;
	system("pause");
	return 0;
}

  

[LeetCode]3 Sum Closet

标签:blog   io   os   ar   for   sp   div   on   log   

原文地址:http://www.cnblogs.com/supernigel/p/4029705.html

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