和3sum类似,使用2 pointer法
题目链接: 3Sum Closest
1. Description
- Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
- Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
2. Two pointer
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int best_nums = nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums.size() - 2; i++){
int first = i + 1;
int end = nums.size() - 1;
while(first < end){
int sum = nums[i] + nums[first] + nums[end];
// find the closest solution using abs
if (abs(sum - target) < abs(best_nums - target)){
best_nums = sum;
}
if (sum == target) // exactly to the closed solution
return sum;
else if (sum < target)
first++;
else if (sum > target)
end--;
// here we need't to erase the duplicate elements
}
}
return best_nums;
}
};
注意
- 最外层的for循环注意终止条件, nums.size()-2, 因为保证3个元素。
- 这里是不需要删除重复的元素的。