LeetCode OJ-18.4Sum(四数和)

LeetCode OJ-18.4Sum(四数和)

题目描述

Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

Subscribe to see which companies asked this question

题目理解

​ 有了三数和的基础,四数和也就比较容易解决了,一样的,固定第1个数与第2个数,剩余两数使用两个迭代器,夹逼求解即可。时间复杂度为O(n^3),比三数和多了一层循环,这里的去重与三数和大同小异。具体代码如下:

Code

vector<vector<int>> four_nums(vector<int> &nums, int target)
{
    vector<vector<int>> res;
    vector<int> tmp;
    sort(nums.begin(), nums.end(), cmp);  //排序方便去重

    int i, j, k, l;
    int sz = (int) nums.size();
    for (i = 0; i < sz - 3; ++i) {  //固定第1个数
        for (j = i + 1; j < sz - 2; ++j) {  //固定第2个数
            k = j + 1;
            l = sz - 1;
            while (k < l) {  //夹逼求解
                if (nums[i] + nums[j] + nums[k] + nums[l] > target) {
                    --l;
                }
                else if (nums[i] + nums[j] + nums[k] + nums[l] < target) {
                    ++k;
                }
                else {
                    tmp.push_back(nums[i]);
                    tmp.push_back(nums[j]);
                    tmp.push_back(nums[k]);
                    tmp.push_back(nums[l]);
                    res.push_back(tmp);
                    tmp.clear();

                    while (++k && nums[k] == nums[k - 1]) ;  //去重
                    while (--l && nums[l] == nums[l + 1]) ;  //去重
                }
            }

            while (j < sz - 2 && nums[j] == nums[j + 1]) {  //第2个数去重
                ++j;
            }

        }

        while (i < sz - 3 && nums[i] == nums[i + 1]) {  //第1个数去重
            ++i;
        }
    }

    return res;
}

int cmp(int __x, int __y)
{
    return __x < __y;
}

你可能感兴趣的:(OJ)