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.

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

其实经过3sum,这一题应该还挺简单的!设置一个gap,根据gap的状态来移动指针

class Solution {
public:
	int threeSumClosest(vector<int> &num,int target) {
		int result=INT_MAX;
		int temp = 0;
		int gap = INT_MAX;
		if (num.size()<3)
			return INT_MAX;
		sort(num.begin(),num.end());
		typedef vector<int>::iterator it;
		it mid;
		it last;
		result = INT_MAX;
		for (it start = num.begin(); start != num.end() - 1;++start)
		{
			if (start != num.begin())
			{
				if (*start == *(start - 1))
					continue;
			}
			mid = start + 1;
			last =  num.end() - 1;
			while (mid<last)
			{
				temp = abs((*start + *mid + *last - target));
				if (gap > temp )
				{
					result = *start + *mid + *last;
					gap = temp;
				}
				if ((*start + *mid + *last - target) < 0)
				{
					++mid;
				}
				else
					--last;
			}
		}
		return result;
	}
};





你可能感兴趣的:(LeetCode,iterator,STL)