Fast javascript solution beats 100%


  • 0
    C
    var threeSum = function(nums) {
        nums = nums.sort(function(a, b) { return a - b; });
        
        var results = [];
        var i, j, k, n = nums.length;
        
        for (i = 0; i < n; ++i) {
            if (i > 0 && nums[i] === nums[i-1]) continue;
            
            for (j = i + 1; j < n; ++j) {
                if (j > i + 1 && nums[j] === nums[j-1]) continue;
                
                for (k = j + 1; k < n; ++k) {
                    if (k > j + 1 && nums[k] === nums[k-1]) continue;
                    
                    if (nums[i] + nums[j] + nums[k] === 0) results.push([nums[i], nums[j], nums[k]]);
                }
            }
        }
        return results;
    };

Log in to reply
 

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