[Leetcode] 3Sum

Posted yanhewu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] 3Sum相关的知识,希望对你有一定的参考价值。

3Sum 题解

原创文章,拒绝转载

题目来源:https://leetcode.com/problems/3sum/description/


Description

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

Example


For example, given array S = [-1, 0, 1, 2, -1, -4],

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

Solution


class Solution {
private:
    vector<vector<int> > twoSum(vector<int>& nums, int end, int target) {
        vector<vector<int> > res;
        int low = 0;
        int high = end;
        while (low < high) {
            if (nums[low] + nums[high] == target) {
                vector<int> sum(2);
                sum[0] = nums[low++];
                sum[1] = nums[high--];
                res.push_back(sum);

                // 去重
                while (low < high && nums[low] == nums[low - 1])
                    low++;
                while (low < high && nums[high] == nums[high + 1])
                    high--;
            } else if (nums[low] + nums[high] > target) {
                high--;
            } else {
                low++;
            }
        }
        return res;
    }
public:
    vector<vector<int> > threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        int size = nums.size();
        if (size < 3)
            return res;
        sort(nums.begin(), nums.end());
        for (int i = size - 1; i >= 2; i--) {
            if (i < size - 1 && nums[i] == nums[i + 1])  // 去重
                continue;
            auto sum2 = twoSum(nums, i - 1, 0 - nums[i]);
            if (!sum2.empty()) {
                for (auto& sum : sum2) {
                    sum.push_back(nums[i]);
                    res.push_back(sum);
                }
            }
        }
        return res;
    }
};

解题描述

这道题是Two Sum的进阶,解法上采用的是先求Two Sum再根据求到的sum再求三个数和为0的第三个数,不过题意要求不一样,Two Sum要求返回数组下标,这道题要求返回具体的数组元素。而如果使用与Two Sum相同的哈希法去做会比较麻烦。

这里求符合要求的2数之和用的方法是,先将数组排序之后再进行夹逼的办法。并且为了去重,需要在2sum和3sum都进行去重。

以上是关于[Leetcode] 3Sum的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 15. 3Sum

leetcode16 3Sum Closest

[Leetcode] 3Sum

4Sum -- LeetCode

LeetCode(16):3Sum Closest

Leetcode 15. 3Sum