Any shortest cpp solution? 212ms accepted


  • 2
    vector<vector<int>> threeSum(vector<int> &num) {
        sort(num.begin(), num.end());
        vector<vector<int>> rs;
    
        for (int i = 0; i < num.size(); i++) {
            // skip identical numbers except the first one
            if (i > 0 && num[i] == num[i - 1])
                continue;
    
            for (int j = i + 1, k = num.size() - 1; j < k;) {
                // skip identical numbers in the front, and numbers which make the sum too small
                if (j > i + 1 && num[j] == num[j - 1] || num[j] + num[k] < -num[i])
                    j++;
                // skip identical numbers at the tail, and numbers which make the sum too large
                else if (k < num.size() - 1 && num[k] == num[k + 1] || num[j] + num[k] > -num[i])
                    k--;
                // so far we get zero sum
                else
                    rs.push_back({ num[i], num[j++], num[k--] });
            }
        }
    
        return rs;
    }

Log in to reply
 

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