标签:
用了和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; } };
标签:
原文地址:http://blog.csdn.net/tspatial_thunder/article/details/38166421