brute force O(n^3)
先排一遍序,遍历两个数,第三个数用二分查找,复杂度O(n^2*lgn)
遍历一个数,第二、三个数用双指针查找,转化为2Sum Closest问题,复杂度O(n^2)
O(n^2lgn)
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
std::sort(nums.begin(),nums.end());
int diff = INT_MAX, toReturn = INT_MAX;
for (int i = 0; i < nums.size() - 2; i++){
for (int j = i+1; j < nums.size() - 1;j++){
int op1 = nums[i];
int op2 = nums[j];
int toFind = target - op1 - op2;
// Now perform binary search in nums[j+1:]
int lo = j+1, hi = nums.size()-1;
while (lo < hi){
int mi = lo + (hi-lo)/2;
if (toFind < nums[(lo+hi)/2]){
hi = mi;
} else if (toFind > nums[(lo+hi)/2]){
lo = mi + 1;
} else {
// We find this
return target;
}
}
// we find the only two candidate, let's check which is the lucky guy.
if (abs(target-op1-op2-nums[hi-1]) < diff && hi-1 > j){
diff = abs(target-op1-op2-nums[hi-1]);
toReturn = op1+op2+nums[hi-1];
}
if (abs(target-op1-op2-nums[hi]) < diff){
diff = abs(target-op1-op2-nums[hi]);
toReturn = op1+op2+nums[hi];
}
}
}
return toReturn;
}
};
O(n^2)
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
std::sort(nums.begin(),nums.end());
int diff = INT_MAX, ans;
for (int i = 0; i < nums.size()-2;i++){
int j = i+1, k = nums.size()-1;
int toFind = target - nums[i];
while (j < k){
if (abs(toFind - nums[j] - nums[k]) < diff){
diff = abs(toFind - nums[j] - nums[k]);
ans = nums[i] + nums[j] + nums[k];
}
if (nums[j] + nums[k] < toFind) j++;
else if (nums[j] + nums[k] > toFind) k--;
else return target;
}
}
return ans;
}
};