LeetCode 16.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).
分析与解答:

跟上个题目相似,这次是找三个数的和最接近给定的数值。也是O(n^2)时间,三个指针就可以了。

class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
    int minDiff = INT_MAX, head = 0, end = 0, sum = 0, minSum = 0;
    sort(num.begin(), num.end()); //排个序先
	for (int i = 0; i < num.size() - 2; i++) {
		head = i + 1;
		end = num.size() - 1;
		while (head < end) {
			sum = num[i] + num[head] + num[end];
			if (abs(sum - target) < minDiff) {
				minDiff = abs(sum - target);
				minSum = sum;
			}
			if (sum - target == 0)
				return sum;
			else if (sum - target > 0) {
				end--;
			} else {
				head++;
			}
		}
	}
	return minSum;
    }
};


你可能感兴趣的:(array,Two,Pointers)