先排序,再暴力找就好了。如果当前元素大于0或者前两个元素和大于0就不用找了。然后结果超时了。
然后借鉴了双指针的解法,发现双指针其实就是把单向循环优化成双向循环。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums){
sort(nums.begin(),nums.end());
vector<vector<int>> v;
for(int i=0;i<nums.size()-2;i++){
if(nums[i]>0||nums.size()<3) break;
if(i!=0 && nums[i]==nums[i-1]) continue;
int head=i+1,tail=nums.size()-1;
while(head <tail){
if(nums[tail]<0) break;
if(nums[i]+nums[head]+nums[tail]==0){
vector<int> tem;
tem.push_back(nums[i]);
tem.push_back(nums[head]);
tem.push_back(nums[tail]);
v.push_back(tem);
head++;
tail--;
while(head<tail && nums[head]==nums[head-1]) head++;
while(head<tail && nums[tail]==nums[tail+1]) tail--;
}else if(nums[i]+nums[head]+nums[tail]>0){
tail--;
while(head<tail && nums[tail]==nums[tail+1]) tail--;
}else{
head++;
while(head<tail && nums[head]==nums[head-1]) head++;
}
}
}
return v;
}
};
结果:
标签:15,tem,nums,三数,back,C++,tail,vector,push From: https://www.cnblogs.com/llllmz/p/18029609