lintcode 四数之和

给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。
注意事项
四元组(a, b, c, d)中,需要满足a <= b <= c <= d
答案中不可以包含重复的四元组。
样例
例如,对于给定的整数数组S=[1, 0, -1, 0, -2, 2] 和 target=0. 满足要求的四元组集合为:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
题目链接:http://www.lintcode.com/zh-cn/problem/4sum/

与上一道题三数之和类似,只不过四数之和多了一个指针,按照这个思路,n数之和都可以这么做。

class Solution {
public:
    /**
     * @param numbers: Give an array numbersbers of n integer
     * @param target: you need to find four elements that's sum of target
     * @return: Find all unique quadruplets in the array which gives the sum of 
     *          zero.
     */
    vector<vector<int> > fourSum(vector<int> nums, int target) {
        // write your code here
        sort(nums.begin(),nums.end());
        vector<vector<int> > res;
        for (int i = 0;i < nums.size() - 3;i++) {
            if (i > 0 && nums[i - 1] == nums[i]) continue;
            if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break;
            for (int j = i + 1;j < nums.size() - 2;j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                if(nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) break;
                int left = j + 1,right = nums.size() - 1;
                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum > target) right--;
                    else if (sum < target) left++;
                    else {
                        res.push_back({nums[i],nums[j],nums[left],nums[right]});
                        do{left++;} while (left < right && nums[left] == nums[left - 1]);
                        do{right--;} while (left < right && nums[right] == nums[right + 1]);
                    }
                }
            }
        }
        return res;
    }
};
    原文作者:yzawyx0220
    原文地址: https://www.jianshu.com/p/0caa7cb7443f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞