Check my 61ms solution, how to improve the style


  • 2
    R
    class Solution {
    public:
        vector<vector<int> > threeSum(vector<int> &num) {
            vector<vector<int> > result;
            sort(num.begin(), num.end());
            int size = num.size();
            for(int i = 0; i < size - 2; i++)
            {
                int num1 = num[i];
                if(i > 0 && num1 == num[i-1])
                    continue;
                int num2, num3;
                int twoSum = 0 - num1;
                int start = i+1, end = size - 1;
                vector<int> partSolution;
                while(start < end)
                {
                    int sum = num[start] + num[end];
                    if(sum == twoSum)
                    {
                        partSolution.push_back(num[start]);
                        partSolution.push_back(num[end]);
                        start++;
                        while(start < size && num[start] == num[start-1])
                        {
                            start++;
                        }
                    }
                    else if(sum < twoSum)
                    {
                        start++;
                    }
                    else
                    {
                        end--;
                    }
                }
                if(!partSolution.empty())
                {
                    for(int i =0; i < partSolution.size(); i+=2)
                    {
                        vector<int> singleSolution(3);
                        singleSolution[0] = num1;
                        singleSolution[1] = partSolution[i];
                        singleSolution[2] = partSolution[i+1];
                        result.push_back(singleSolution);
                    }
                }
            }
            
            return result;    
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.