思路:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int res = 10000;
int tmp = 0;
int len = nums.size();
for(int i = 0; i < len; i++){
for(int j = i+1; j < len; j++){
for(int k = j+1; k < len; k++){
if(res > abs(target - nums[i] - nums[j] - nums[k])){
res = abs(target-nums[i] - nums[j] - nums[k]);
tmp = nums[i] + nums[j] + nums[k];
}
}
}
}
return tmp;
}
};
- 类似3Sum。这几道题相对暴力能够减小复杂度的主要原因是暴力里面的两层循环都执行了,而后面的这种解法通过比较使内部的两层循环减少到了一层,所以时间复杂度由 (O(n^3)) 减小到了 (O(n^2))。
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int res = 100000;
int tmp = 0;
sort(nums.begin(), nums.end());
int len = nums.size();
for(int i = 0; i < len-2; i++){
int lo = i+1,hi = len-1;
while(lo < hi){
if(abs(nums[i] + nums[lo] + nums[hi] - target) < res){
res = abs(nums[i] + nums[lo] + nums[hi] - target);
tmp = nums[i] + nums[lo] + nums[hi];
}
if(nums[i] + nums[lo] + nums[hi] == target) return target;
else if (nums[i] + nums[lo] + nums[hi] > target){
hi--;
}
else lo++;
}
}
return tmp;
}
};