每日leetcode(34)
15. 三数之和
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
这道题如果三个循环暴力解决是超时的,使用双指针法
上图来自题解大佬,最后一个图说的结束遍历是指开始下一轮遍历
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
if(nums.size()<=2) return res; //只有两个数返回
int numSize=nums.size();
int vecSize=numSize-2;
sort(nums.begin(),nums.end());
for(int i=0;i<vecSize;i++){
if(nums[i]>0) break; //三个数中最小的数大于0,所以和不可能为0,不用继续
if(i>0 && nums[i]==nums[i-1]) continue; //去重,后一个数和当前数相等,跳过
int low=i+1; //左指针
int high=numSize-1; //右指针
while(low<high){
if(nums[low]+nums[high]+nums[i]>0){ //和大于0
while(low<high && nums[high]==nums[--high]); //右指针左移,注意,这里不管前一个数和当前指针是否相同都要左移
}
else if(nums[low]+nums[high]+nums[i]<0){
//low++;
while(low<high && nums[low]==nums[++low]); //左指针右移,注意,这里不管后一个数和当前指针是否相同都要右移
}
else{
vector<int> temp{nums[i],nums[low],nums[high]};
res.push_back(temp);
while(low<high && nums[low]==nums[++low]); //同上
while(low<high && nums[high]==nums[--high]); //同上
}
}
}
return res;
}
};
140ms