https://leetcode.com/problems/3sum-closest/
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 1:
- Input: nums = [-1,2,1,-4], target = 1
- Output: 2
- Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Constraints:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
算法思路:
如果当前数组不排序,那么取其中任意三个得到curSum,与target比较,C(n,3)=n*(n-1)*(n-2)/6,时间复杂度是O(n^3),不用想肯定超时,所以和前面twoSum等问题类似,先排序( O(n logn) ),然后先固定一个,另外两个使用双指针技术,使得时间复杂度降为O(n^2)。
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
int left=0;
int right=nums.size()-1;
int diff=INT_MAX;
int res=INT_MAX;
int curSum=0;
for(int i=0;i<nums.size()-2;i++){ //O(n^2)
left=i+1;
right=nums.size()-1;
while(left<right){
curSum=nums[i]+nums[left]+nums[right];
if(curSum==target){
return target;
}
if(curSum>target){
if(diff>curSum-target){
diff=curSum-target;
res=curSum;
}
right--;
}else{ //curSum<target
if(diff>target-curSum){
diff=target-curSum;
res=curSum;
}
left++;
}
}
}
return res;
}
};