leetcode 15 3Sum

Posted by lsq on November 11, 2018

题干

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]
]

题解1 two pointer 35.37%

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int> > res;
        sort(nums.begin(), nums.end());
        for(int i=0; i<nums.size(); i++)
        {
            int front = i + 1; 
            int back = nums.size() - 1;
            while(front < back)
            {
                int sum = nums[front] + nums[back];
                if(sum + nums[i] < 0) front++;
                else if (sum + nums[i] > 0) back--;
                else
                {
                    vector<int> temp(3,0);
                    temp[0] = nums[i];
                    temp[1] = nums[front];
                    temp[2] = nums[back];
                    res.push_back(temp);
                    
                    while(front < back && nums[front] == temp[1]) front++;
                    while(front < back && nums[back] == temp[2]) back--;
                }   
            }
            while(i < nums.size() - 1 && nums[i] == nums[i+1]) i++;
        }
        
        return res;
    }
};