其他分享
首页 > 其他分享> > leetcode——18.四数之和

leetcode——18.四数之和

作者:互联网

思路

  1. 三数之和基础上加多了一层遍历

代码

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> ans;
        sort(nums.begin(),nums.end());
        int n=nums.size();
        for(int first=0;first<n-1;first++){
        	//保留重复数组中的第一个元素
            if(first>0&&nums[first]==nums[first-1])
                continue;
            for(int second=first+1;second<n;second++){
            	//保留重复数组中的第一个元素
                if(second>first+1&&nums[second]==nums[second-1])
                    continue;
                //转为两数之和问题 双向指针遍历
                int third=second+1,fourth=n-1;
                while(third<fourth){
                    int sum=nums[first]+nums[second]+nums[third]+nums[fourth];
                    if(sum>target)
                        fourth--;
                    else if(sum<target)
                        third++;
                    else{
                        ans.push_back({nums[first],nums[second],nums[third],nums[fourth]});
                        //移动third fourth指针 跳过重复元素
                        int third_val=nums[third];
                        int fourth_val=nums[fourth];
                        do{third++;}
                        while(third<fourth&&third_val==nums[third]);
                        do{fourth--;}
                        while(third<fourth&&fourth_val==nums[fourth]);
                    }
                }
            }
        }
        return ans;
    }
};

标签:四数,third,nums,int,18,second,fourth,leetcode,first
来源: https://blog.csdn.net/Dedication_/article/details/118276668