给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。

四元组(a, b, c, d)中,需要满足a <= b <= c <= d

答案中不可以包含重复的四元组。
vector<vector<int> > fourSum(vector<int> nums, int target) {
        vector<vector<int>> res;
        if (nums.size() < 4) {
            return res; 
        }
        sort(nums.begin(), nums.end()); 
        
        for (int first = 0; first < nums.size() - 3;) {
            for (int second = first + 1; second < nums.size() - 2;) {
                int third = second + 1;
                int fourth = nums.size() - 1;
                
                while (third < fourth) {
                    int sum = nums[first] + nums[second] + nums[third] + nums[fourth]; 
                    if (sum == target) {
                        res.push_back({nums[first], nums[second], nums[third], nums[fourth]}); 
                        ++third;
                        while (third  < fourth && nums[third - 1] == nums[third]) {
                            ++third; 
                        } 
                    } else if (sum < target) {
                        ++third;
                    } else {
                        --fourth;
                    }
                }
                ++second;
                while (second < nums.size() && nums[second - 1] == nums[second]) {
                    ++second; 
                }
            }
            ++first;
            while (first < nums.size() && nums[first - 1] == nums[first]) {
                    ++first; 
            }
        }
    }

shiyang6017
158 声望59 粉丝

« 上一篇
链表求和
下一篇 »
表达式的值