15. 3Sum[Medium]

Given an array nums of n integers, are there elements a, b, c in nums 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:

Given array nums = [-1, 0, 1, 2, -1, -4],

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

using namespace std;

class Solution {
public:
    vector< vector > twoSum(vector& nums, int begin, int flag) {
        vector< vector > result;
        for(int i = begin + 1, j = nums.size()-1; i < j; )
        {
            if(i>begin+1&&nums[i]==nums[i-1])
            {
                i++;
                continue;
            }
            int target = 0 - flag;
            if(nums[i]+nums[j] == target)
            {
                vector temp;
                temp.push_back(flag);
                temp.push_back(nums[i]);
                temp.push_back(nums[j]);
                result.push_back(temp);
                j--;
                i++;

            }
            else if(nums[i]+nums[j] > target)
            {
                j--;
            }
            else
            {
                i++;
            }
        }

        return result;
    }


    vector< vector > threeSum(vector& nums) {
        sort(nums.begin(), nums.end());
        vector< vector > result;
        for(int i = 0; i < nums.size(); i++)
        {
            if(i>0&&nums[i]==nums[i-1]) continue;
            vector< vector > temp = twoSum(nums, i, nums[i]);
            result.insert(result.end(), temp.begin(), temp.end());
        }
        return result;
    }
};
Runtime: 136 ms, faster than 37.19% of C++ online submissions for 3Sum.
Memory Usage: 22.2 MB, less than 20.34% of C++ online submissions for 3Sum.
思路
  • 先排序,遍历,然后转化为2sum问题

你可能感兴趣的:(15. 3Sum[Medium])