其他分享
首页 > 其他分享> > LeetCode 3Sum 双指针

LeetCode 3Sum 双指针

作者:互联网

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Solution

我们需要输出方案,不在乎下标,但是不能有重复的。不妨先排序,然后利用遍历第一个选择 \(nums[i]\),剩下的 \(j,k\) 利用双指针(从 \(l=i+1,r=n-1\) 开始),如果此时的 \(sum>0\),意味着右指针左移 \(r-=1\);否则左指针右移 \(l+=1\)

点击查看代码
class Solution {
private:
    vector<vector<int>> ans;
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int n = nums.size();
        sort(nums.begin(),nums.end());
        for(int i=0;i<n-2;i++){
            
            int l = i+1, r = n-1;
            if(i!=0 && nums[i]==nums[i-1])continue;
            
            while(l<r){
                vector<int> tmp;
                int ck = nums[i]+nums[l]+nums[r];
                if(ck==0){
                    tmp.push_back(nums[i]);
                    tmp.push_back(nums[l]);
                    tmp.push_back(nums[r]);
                    ans.push_back(tmp);
                    
                    // remove duplicated
                    while(r-1>=l && nums[r-1]==nums[r])r--;
                    while(l+1<r && nums[l+1]==nums[l])l++;
                    r--;l++;
                    
                }
                
                else if(ck>0) r--;
                else l++;
            }
        }
        return ans;
    }
};

标签:tmp,nums,3Sum,back,int,push,LeetCode,指针
来源: https://www.cnblogs.com/xinyu04/p/16464623.html