Title Description:
Given an array S of n integers, find three integers in S such, the sum was closest to a Given number, target. Return the sum of the three integers. You may assume this each input would has exactly one solution.
Example:
For example, given array S = {-1 2 1-4}, and target = 1.
The sum is closest to the target is 2. (-1 + 2 + 1 = 2).
Analysis:
Test instructions: Given an array of n integers and a target value of targets, find the unique solution triples (A, B, c), making the A+b+c and target closest.
Idea: This question and Leetcode , just give a target goal value, we only need to make some improvements in the details: ① when sum equals target, find the unique solution, return directly; ② at this time sum is not equal to target, Then determine whether the gap between them is reduced, and if so, update the answer ans and the corresponding Gap delta. The other treatment methods are not changed.
The time complexity is O (NLOGN) +o (n²) =o (n²).
Code:
#include <bits/stdc++.h> using namespace std;
Class Solution {private:static int cmp (const int A, const int b) {return a < b;
} public:int threesumclosest (vector<int>& nums, int target) {int n = nums.size ();
Exceptional Case:if (n <= 2) {return 0;
}//Sort sort (nums.begin (), Nums.end (), CMP);
int ans, delta = int_max;
int left, right;
for (int i = 0, I <= n-3;) {left = i + 1;
right = n-1;
BOOL flag = FALSE;
while (left < right) {int sum = Nums[i] + nums[left] + nums[right]; Debug//cout << ' sum: ' << sum << ', I: ' << i << ', left: ' << left <<
' Right: ' << right << Endl;
if (sum = = target) {ans = sum;
Flag = true;
Break
} else if (sum < target) {//Check if (Target-sum < delta) {delta = target-sum;
ans = sum;
} left++; while (left < right && numS[left] = = Nums[left-1]) {left++;
}} else if (Sum > Target) {//Check if (Sum-target < delta) {delta = sum-target;
ans = sum;
} right--;
while (left < right && nums[right] = = nums[right + 1]) {right--;
}}} if (flag) {break;
} i++;
while (i <= n-3 && nums[i] = = Nums[i-1]) {i++;
}} return ans; }
};