solution.cpp 883 字节
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#include <cstdlib>
class Solution
{
public:
	int threeSumClosest(vector<int> &nums, int target)
	{
		sort(nums.begin(), nums.end());
		int cur, left, right;
		cur = 0;
		int closest = nums[0] + nums[1] + nums[2];
		while (cur < nums.size() - 2)
		{
			left = cur + 1;
			right = nums.size() - 1;
			int n;
			while (left < right)
			{
				n = nums[cur] + nums[left] + nums[right];
				if (abs(target - n) < abs(target - closest))
				{
					closest = n;
				}
				if (n == target)
				{
					break;
				}
				else if (n > target)
				{
					int t = right - 1;
					while (t > left && nums[t] == nums[right])
						t--;
					right = t;
				}
				else
				{
					int t = left + 1;
					while (t < right && nums[t] == nums[left])
						t++;
					left = t;
				}
			}
			int t = cur + 1;
			while (t < nums.size() && nums[t] == nums[cur])
				t++;
			cur = t;
		}
		return closest;
	}
};