[Leetcode] 3sum

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
    
        vector<vector<int> > res;
        sort(num.begin(), num.end());
                
        if (num.size() < 3) return res;

        
        vector<int> temp(3);
        for (int k = 0; k < num.size() - 2; ++k)
        {
            int i = k + 1;
            int j = num.size() - 1;
            
            while (i < j)
            {
                if (num[k] + num[i] + num[j] > 0)
                    --j;
                else if (num[k] + num[i] + num[j] < 0)
                    ++i;
                else
                {
                    temp[0] = num[k];
                    temp[1] = num[i];
                    temp[2] = num[j];
                
                    res.push_back(temp);
                    ++i; --j;
                }
            }
        }
        sort(res.begin(), res.end());
        res.erase(unique(res.begin(), res.end()), res.end());
        return res;
    }
};

你可能感兴趣的:([Leetcode] 3sum)