It uses the same idea as 3sum, and binary search. The key is pruning, but many mistakes have been made in pruning.
Then there was a faster idea O (N ^ 2 ).
#include<iostream> #include <vector> #include <algorithm> #include <math.h>using namespace std;class Solution {public:int threeSumClosest(vector<int> &num, int target) {int minDis = 1 << 30;int closetSum = -1<<30;sort(num.begin(), num.end());for (int i = 0; i < num.size() - 2; i++){for (int j = i + 1; j < num.size() - 1; j++){int twoSum = num[i] + num[j];int value = target - twoSum;int tmpCloVal = searchValue(num, j + 1, num.size() - 1, value);if (abs(target - twoSum - tmpCloVal) < minDis){closetSum = twoSum + tmpCloVal;minDis = abs(target - closetSum);}if ( num[j+1]>0 && num[i]+num[j] > target)break;}if (num[i+1]>0 && num[i] > target)break;}return closetSum;}int searchValue(vector<int> num, int left, int right, int value){const int l = left, r = right;int closetVal;int m;if (value > num[right])return num[right];else if (value < num[left])return num[left];while (left <= right){m = (left + right) / 2;if (num[m] <= value && num[m + 1] >= value){break;}else if (num[m] < value){left = m + 1;}else{right = m - 1;}}closetVal = num[m];if (abs(closetVal-value) > abs(num[m + 1] - value)){closetVal = num[m+1];}if (abs(closetVal - value) > abs(num[m-1]-value)){closetVal = num[m - 1];}return closetVal;}};
Leetcode 3sum closet