首页 > 其他分享 >LeetCode 15. 三数之和

LeetCode 15. 三数之和

时间:2023-03-14 15:37:08浏览次数:36  
标签:15 nums int 三数 vector && res LeetCode

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        sort(nums.begin(),nums.end());
        int n=nums.size();
        for(int i=0;i<n;i++)
        {
            if(i&&nums[i]==nums[i-1]) continue;
            for(int j=i+1,k=n-1;k>j;j++)//寻找两数之和等于sum
            {
                if(j>i+1&&nums[j]==nums[j-1])   continue;
                while(k>j&&nums[k]+nums[j]+nums[i]>0)   k--;
                if(k>j&&nums[k]+nums[j]+nums[i]==0)
                    res.push_back({nums[k],nums[j],nums[i]});
            }
        }
        return res;
    }
};

标签:15,nums,int,三数,vector,&&,res,LeetCode
From: https://www.cnblogs.com/tangxibomb/p/17215013.html

相关文章