题目:
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).
解题思路:
枚举第一个数,另外两个数:一个在第一个数后边一个开始,一个从末尾开始,和4Sum类似调整。复杂度:O(n^2)。
代码:
1 class Solution { 2 public: 3 int threeSumClosest(vector<int> &num, int target) { 4 int ans = 0; 5 bool findans = false; 6 sort(num.begin(), num.end()); 7 for (int first = 0; first < num.size(); first++){ 8 for (int second = first + 1, third = num.size() - 1; second < third; ){ 9 int tmp_sum = num[first] + num[second] + num[third]; 10 if (tmp_sum < target){ 11 second ++; 12 } 13 if (tmp_sum > target){ 14 third --; 15 } 16 if (tmp_sum == target){ 17 return tmp_sum; 18 } 19 20 if (!findans || (abs(tmp_sum - target) < abs(ans - target))){ 21 ans = tmp_sum; 22 findans = true; 23 } 24 } 25 } 26 return ans; 27 } 28 };