二手和3Sum像几乎相同的想法。二进制搜索。关键修剪。但是,在修剪做出很多错误。
然后还有一个更加速了原来的想法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; } };
版权声明:本文博主原创文章。博客,未经同意不得转载。