15三数之和
题目链接:https://leetcode-cn.com/problems/3sum/
这个题目也是双指针,两数之和的加强版。虽然很明显最优解是 O ( n 2 ) O(n^{2}) O(n2)的,但是关键在于怎样能够在其他地方节省时间。比如这一题中不需要重复的解(也就是一模一样的三数组合),如果采用和现有解空间对比的法子就太慢了,如果可以找到方法跳过重复的数,就会好很多。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(),nums.end());
vector<int> tem_nums=nums;
int i=0;
int j=tem_nums.size()-1;
int k=0;
int l=0;
vector<int> tem_vector={};
bool exist=false;
for(k=0;k<tem_nums.size();){
i=k+1;
j=tem_nums.size()-1;
while(i<j){
if(tem_nums[i]+tem_nums[j]>-tem_nums[k]){
do{
--j;
} while(j>i&&tem_nums[j+1]==tem_nums[j]);
}
else if(tem_nums[i]+tem_nums[j]<-tem_nums[k]){
do{
++i;
} while(j>i&&tem_nums[i-1]==tem_nums[i]);
}
else{
cout<<k<<i<<j<<endl;
tem_vector={};
tem_vector.push_back(tem_nums[k]);
tem_vector.push_back(tem_nums[i]);
tem_vector.push_back(tem_nums[j]);
result.push_back(tem_vector);
do{
++i;
} while(j>i&&tem_nums[i-1]==tem_nums[i]);
do{
--j;
} while(j>i&&tem_nums[j+1]==tem_nums[j]);
}
}
do{
++k;
}while(k<tem_nums.size()&&tem_nums[k-1]==tem_nums[k]);
}
return result;
}
};
第十六题和这个做法一样,不过不需要进行重复检验(题设说假设有唯一解)
题目链接:https://leetcode-cn.com/problems/3sum-closest/
代码:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int result=nums[0]+nums[1]+nums[2];
int distance=abs(nums[0]+nums[1]+nums[2]-target);
int i=0;
int j=0;
int k=0;
sort(nums.begin(),nums.end());
for(k=0;k<nums.size()-2;++k){
i=k+1;
j=nums.size()-1;
while(i<j){
if(abs(nums[k]+nums[i]+nums[j]-target)<distance){
result=nums[k]+nums[i]+nums[j];
distance=abs(nums[k]+nums[i]+nums[j]-target);
}
if(nums[k]+nums[i]+nums[j]>target)
--j;
else if(nums[k]+nums[i]+nums[j]<target)
++i;
else
break;
}
}
return result;
}
};